문제

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top