I think you might be overthinking the solution..
foreach ($data->results->data->team as $team_id => $team_data) {
// $team_id holds the index of the teams array
echo $team_id;
echo $team_data->name;
echo $team_data->id;
}
سؤال
This is the output that I'm trying to access:
stdClass Object
(
[results] => stdClass Object
(
[columns] => stdClass Object
(
[name] => Name
[id] => id
)
[data] => stdClass Object
(
[team] => Array
(
[0] => stdClass Object
(
[name] => Kansas City
[id] => 47556332
)
[1] => stdClass Object
(
[name] => Chi White Sox
[id] => 03948575
)
[2] => stdClass Object
(
[name] => Detroit
[id] => 3747646625
)
)
)
)
)
)
I'm trying to get the id of this, but I'm running into troubles with accessing anything after the 0+. I have two foreach loops here because I need to iterate through the name and id and place them in a table, but I have no problem doing that. I just need to get at whatever is inside the [0]. How do I reference that 0?
foreach ($data->results->data->team as $team_data) {
foreach ($team_data->THE ID/NUMBER->name as $team_id) {
#code...
}
}
When I do the code above, I get so so many errors. I've tried different ways and keep getting an error in the form of:
Notice: Undefined property: stdClass::$0 in index.php on line 61 Notice: Trying to get property of non-object in index.php on line 61
This error is from trying a $id, and $id++ to get the numbered part. I know this question has been asked before, but I need to get through multiple numbers and not just 0, because apparently
$team_data->{'0'}->name
would work for just one, but I get errors even trying to do that, and I need to get 0, 1, 2, etc.
المحلول
I think you might be overthinking the solution..
foreach ($data->results->data->team as $team_id => $team_data) {
// $team_id holds the index of the teams array
echo $team_id;
echo $team_data->name;
echo $team_data->id;
}
نصائح أخرى
$team_data is already the object with name and id in it. So skip the second foreach
and access $team_data['id'] and $team_data['name'] directly