Asked by: Ana Cláudia Gomes
So, I have this array of arrays, something like this:
protected static $base = [
[
'id' => 4,
'createdAt' => 1498638933,
'title' => 'Example 1',
'tables' => [
['title' => '#1', 'createdAt' => 1498638940],
['title' => '#2', 'createdAt' => 1498638941],
['title' => '#3', 'createdAt' => 1498638943],
],
],
[
'id' => 7,
'createdAt' => 1498643923,
'title' => 'Example 2',
'tables' => [
['title' => '#1', 'createdAt' => 1498643925],
['title' => '#2', 'createdAt' => 1498643929],
['title' => '#3', 'createdAt' => 1498643932],
],
these arrays are in a Model code, and I want to display them in my page. Also, from the Model:
public static function getAll() {
sleep(1);
return self::$base;
}
From web.php (routes), I have:
Route::get('/', function () {
$items = \App\MyModel::getAll();
return view('welcome')->with('items', $items);
});
Now, if I try:
{!! dd($items) !!}
All the arrays are displayed, but not in a pretty way. I want only their content. So, I followed these steps (https://laracasts.com/discuss/channels/general-discussion/passing-arrays-to-blade-and-iterating) which became:
@foreach($items['title'] as $title => $content)
{{ $title }}
@foreach ($content as $tables => $item)
{{ $tables . ' => ' . $item }}
@endforeach
@endforeach
But 'title' isn't recognized, and I've tried some things like this, nothing works. What I might be missing?
Answers
Answered by: Peter Featherstone at 2017-07-11 05:25AM Accepted
You are trying to loop over an array key inside an array of arrays which is not possible.
You first need to loop through the outer arrays and then you can access the content of the keys inside such as below:
@foreach($items as $item)
{{ $item['title'] }}
@foreach($item['tables'] as $table)
{{ $table['title'] }}
@endforeach
@endforeach
Answered by: Youness Arsalane at 2017-07-11 05:30AM
First of all, if you return variables with a view, you can better use php's compact function so you won't repeat yourself. Here's an example:
return view('welcome', compact('items'));
And since you use dd() it dumps everything in the array and then dies. If you want to show all items you should indeed use a foreach loop, but like this:
@foreach($items as $item)
{{ $item['title'] }}
@foreach($item['tables'] as $table)
{{ $table['title'] }}
@endforeach
@endforeach
No comments:
Post a Comment