Home > front end >  nested triple array with foreach php-laravel
nested triple array with foreach php-laravel

Time:08-17

I have nested arrays, I want to return them with foreach but when I get to 3rd array I get an error.

Error output: htmlspecialchars(): Argument #1 ($string) must be of the given array type

Following my code:

 $array = array(
            "fruits" => array("Apple" => array("Sweet Apple", "Sour Apple") , "Orange", "Pear"),
            "vegetables" => array("Pepper" => array("Hot Pepper", "Sweet Pepper"), "Onion", "Aubergine"),
            "names"  => array("John", "Smith")
        );

@foreach($array as $key => $value)
    {{ $key }}
    @foreach($value as $secondValue)
        <li>{{ $secondValue }}</li>

        @foreach($secondValue as $thirdKey => $thirdValue)
            <li>{{ $thirdValue }}</li>
        @endforeach

    @endforeach
@endforeach

dd output :

enter image description here

CodePudding user response:

Since you wanted to print in parent child like relationship below code should work fine

 $array = [
    "fruits" => ["Apple" => ["Sweet Apple", "Sour Apple"] , "Orange", "Pear"],
    "vegetables" => ["Pepper" => ["Hot Pepper", "Sweet Pepper"], "Onion", "Aubergine"],
    "names"  => ["John", "Smith"]
 ]
  

@foreach($array as $key => $value)
    {{ $key }}
    <ul>
    @if(is_array($value))
    @foreach($value as $name => $secondValue)
        <li>
            {{ is_array($secondValue) ? $name : $secondValue }}
            @if(is_array($secondValue))
            <ul>
                @foreach($secondValue as $thirdKey => $thirdValue)
                    <li>{{ $thirdValue }}</li>
                @endforeach
            </ul>
            @endif    
        </li>
    @endforeach
    @endif
    </ul>
@endforeach

As for why your implementation gave error is that the $secondValue will sometimes have array sometimes string. If it's string you will encounter an error since the foreach expects array to be it's parameter. You are encountering error on Orange of fruits key.

  • Related