Reputation: 7
I am trying to iterate through the values of a JSON ARRAY with no success. When the file has a single value, I loop through it with no problem.
Controller
$data = '[{
"T": {
"HD": {
"HD01": "1",
"HD02": "06033942",
"HD03": "3736803"
}
}
}]';
$data = json_decode($data);
return view('dashboard.book.index', ['data' => $data[0]]);
Blade
<tbody>
@foreach($data as $item)
<tr>
@foreach($item->HD as $title)
<td>{{ $title }}</td>
@endforeach
</tr>
@endforeach
<tbody>
Result
But when it starts to have more than one value, I can't get the same results:
Controller
$data = '[{
"T": {
"HD": {
"HD01": "1",
"HD02": "06033942",
"HD03": "3736803"
}
}
},
{
"T": {
"HD": {
"HD01": "2",
"HD02": "06035419",
"HD03": "4736521"
}
}
}]';
$data = json_decode($data);
return view('dashboard.book.index', ['data' => $data]);
Result
With $data[0] I get the values individually, but when I want to send the whole array I get errors.
How can I modify my code to make it work?
Upvotes: 0
Views: 1177
Reputation: 10220
It might be easier to convert the JSON
to an associative array and then to a Laravel collection
in order to use some of the helper methods available.
So for example:
return view('dashboard.book.index', [
'data' => collect(json_decode($data, true))->flatten(2)
]);
Then in your blade view file:
<table>
<tr>
@foreach ($data->first() as $key => $value)
<th>{{ $key }}</th>
@endforeach
</tr>
@foreach ($data as $items)
<tr>
@foreach ($items as $key => $value)
<td>{{ $value }}</td>
@endforeach
</tr>
@endforeach
</table>
If you want to remove certain keys from the $data
variable, you could do the following:
$keysToRemove = ['HD02', 'HD06'];
$data = collect(json_decode($data, true))
->flatten(2)
->map(function ($array, $key) use ($keysToRemove) {
foreach ($keysToRemove as $key) {
if (array_key_exists($key, $array)) {
unset($array[$key]);
}
}
return $array;
});
return view('dashboard.book.index', [
'data' => $data
]);
Upvotes: 1
Reputation: 1195
On your controller:
$data = json_decode($data, true);
The second parameter When true, returned objects will be converted into associative arrays.
Upvotes: 0