David David - 7 months ago 43
PHP Question

Loop through JSON Array and display results in table - Laravel 5.2

This question probably has been asked many times, but i cant get a solution.

I'm calling to a API like this:

public function getLeaderBoardArray($leaderBoardStats) {
$array = [];
$ex = $leaderBoardStats;

dd($ex);

return $array;
}


This is the result I get when I (DD) (Die-Dump it):

{#201 ▼
+"Start": 0
+"Count": 100
+"ResultCount": 100
+"Results": array:100 [▼
0 => {#199 ▼
+"Player": {#186 ▼
+"Gamertag": "Ferro2Clutch"
+"Xuid": null
}
+"Rank": 1
+"Score": {#195 ▶}
}
1 => {#188 ▶}
2 => {#200 ▶}
3 => {#203 ▶}
4 => {#206 ▶}
5 => {#209 ▶}
6 => {#212 ▶}
....... and so on till 100


How can a loop through this array and display Players Gamertag.

This i what I'm doing right now:

public function getLeaderBoardArray($leaderBoardStats) {
$array = [];
$array['Gamertag_1'] = $leaderBoardStats->Results[0]->Player->Gamertag;
$array['Csr_1'] = $leaderBoardStats->Results[0]->Score->Csr;

$array['Gamertag_2'] = $leaderBoardStats->Results[1]->Player->Gamertag;
$array['Csr_2'] = $leaderBoardStats->Results[1]->Score->Csr;

// and so on til 10....

return $array;
}


As you can see, this would be a pain to do till 100 for each leader-board.

Is there an easier method like somehow doing a for each loop?

Answer

You asked a very similar question yesterday and I'm going to give you a very similar answer today.

https://laravel.com/docs/5.2/collections

Use the map() Collection functionality to convert each item to a more digestable array.

$results = collect($leaderBoardStats->Results);
$gamers  = $results->map(function($item, $key)
{
    return [
        'gamertag' => $item->Player->Gamertag,
        'csr'      => $item->Score->Csr,
    ]
});

This will give you an array that looks like ...

[
    ['gamertag' => "name", 'csr' => 11111],
    ['gamertag' => "name", 'csr' => 11111],
    ['gamertag' => "name", 'csr' => 11111],
    ['gamertag' => "name", 'csr' => 11111],
];

Then, in your view, you can do this to build a table.

@foreach ($gamers->all() as $gamer)
<tr>
    <td>{{ $gamer['gamertag'] }}</td>
    <td>{{ $gamer['csr'] }}</td>
</tr>
@endforeach

All it takes. Laravel Collections are probably one of the strongest aspects of the entire framework and are incredibly robust and well built. If you have an array-related question, chances are that documentation has a collection-related answer.