0

This is probably really simple, but it's kicking my butt..

I have a json array containing around 5,000 video items by id, category, title, score, review. arranged by descending id.

I'm foreach-ing through the array, to create new arrays based on the category (there are 10 categories) to later loop through.

 foreach ($array as $item) {  // the original array
 $cid=$item['category'];
 $chanmov[$cid]['id'][]=$item['id'];
 $chanmov[$cid]['title'][]=$item['title'];
 $chanmov[$cid]['score'][]=$item['score'];
 $chanmov[$cid]['review'][]=$item['review'];
 }

Later I want to loop through the category ids, and pull out the list of that categorys videos video id, title, score,review.

If I print_r by a category id manually - e.g. print_r($chanmov['9']) I get an array of data exactly as expected.

However, where I'm falling over is how to later loop back through the values and pull out the info

e.g. CATEGORY ACTION

id        title            score    review
1753 - Demolition Man [1993] -  5    -  not bad
2123 - Death Wish [1974]     - 10    -  Awesome
3748 - Point Break [1991]   - 6      -  pretty good

I've tried ( '$chid' is each category id )

foreach($chanmov['$chid'] as $movie) {
echo $movie['id']." - ".$movie['title']."<br/>";
}

That gives an "Invalid argument supplied for foreach()" error.

I've tried so many combinations that my head is spinning, I also tried while loops (after changing the first loop to add a counter) but nothing is working.

I know this should not be this hard...

BTW, I HATE arrays..

Any help sincerely appreciated

1
  • 1
    You aren't creating an array for each category. You are creating 4 arrays for each category. So, I think you want to change how you create the structure. Commented Jan 28, 2019 at 21:31

1 Answer 1

1

It seems you really want to make your structure like this:

foreach ($array as $item) {  // the original array
    $cid=$item['category'];
    $chanmov[$cid][]=$item;
}

And then your final loop for a given $chid would be:

foreach($chanmov[$chid] as $movie) {
    echo $movie['id']." - ".$movie['title']."<br/>";
}
Sign up to request clarification or add additional context in comments.

1 Comment

Oh boy.. Of course. That works great. Thank you. Sorry, I can't upvote you because not enough points.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.