So I have a large array called $categoryData that is structured like so:
array: [
123=> array:[
total:[
red=> 155
blue=> 200
]
]
456=> array:[
total:[
red=> 678
blue=> 443
]
]
376=> array:[
total:[
red=> 843
blue=> 456
]
]
236=> array:[
total:[
red=> 456
blue=> 890
]
]
]
That's fine, and now I'm looping it to basically set an object to the array for the correct index, in this case 123. So I'm doing this:
foreach($categoryData as $data){
if($data[0] == 123){
$printData = $data[0];
}
}
dd($printData);
This is giving me undefined offset: 0
error and I'm not sure why. I'm getting the correct structure if I dump it within the foreach loop so all I want to do is set the array for the index to $printData
when it matches, if that makes sense
What am I doing wrong?
My Answer:
You are trying to access the index 0 of the $data array, but $data is an associative array and does not have numerical indexes like 0, 1, 2, etc. Instead, you should access the index 'total' and then access the 'red' and 'blue' keys within the 'total' array.
Here is the corrected code:
php
foreach($categoryData as $key => $data){
if($key == 123){
$printData = $data['total'];
}
}
dd($printData);
This code will set $printData to the 'total' array for the index 123 in the $categoryData array.
Rate this post
4 of 5 based on 2633 votesComments