Ad

PHP (Laravel): Foreach Loop With Nested Array

- 1 answer

I have an array with this kinda hierarchy:

file structure

I need do display the content from the JSON file inside my blade view. I want to use the information laying inside name, url, item in order to display categories. The content inside "item" is something I need, in order to display additional information about products.

How can I print these results ? I tried to use an foreach loop with Blade Syntax, but I can't manage to access the correct results (or all results). //Illegal string offset 'name'

My try so far:

@php
$path = storage_path() . "/app/public/data.json";
$json = json_decode(file_get_contents($path), true);
@endphp


@foreach ($json['collection'] as $content)
<p>Name {{ $content['name'] }}</p>
<p>Url {{ $content['url'] }}</p>
<p>Item {{ $content['item'] }}</p>
@endforeach
Ad

Answer

  <p>Name {{ $json['collection']['name'] }}</p>
  <p>Url {{ $json['collection']['url'] }}</p>
  @foreach ($json['collection']['item'] as $data)
   <p> Format {{ $data['format'] }}</p>
   <p> Author {{ $data['author'] }}</p>
  @endforeach

Please try the above solution.

The reason you're getting the Illegal string offset 'name' following error because it's looping JSON collections. The first time it went on the loop it found to name but when it looped the second time it's pointing to the URL, not the name.

Ad
source: stackoverflow.com
Ad