How to access nested array values

后端 未结 6 1802
轮回少年
轮回少年 2021-01-26 18:03

I have the following array that I need to use in a laravel email view template

$inputs[\'test\']

Which looks like this when I dd($inputs[

相关标签:
6条回答
  • 2021-01-26 18:05

    First you have what is key and what is value of arrays
    They are multiple ways to echo arrays this is one way

    foreach($inputs['test']['order'] as $key =>  $test){
            echo 'Key ->'.$key.'<br/>';    
            echo 'Value ->'. $test. '<br/>';
        }
    
    0 讨论(0)
  • 2021-01-26 18:07

    Try

    $inputs['test']['order'][0]

    Basically, php reads the nested arrays as arrays in arrays .. so no matter how many arrays nested you can always use [][][][][]

    php manual

    Example #6 Accessing array elements

    <?php
    $array = array(
        "foo" => "bar",
        42    => 24,
        "multi" => array(
             "dimensional" => array(
                 "array" => "foo"
             )
        )
    );
    
    var_dump($array["foo"]);
    var_dump($array[42]);
    var_dump($array["multi"]["dimensional"]["array"]);
    ?>
    

    and you can use it in looping as such

    foreach($inputs['test']['order'] as $test){
        echo $test;} 
    
    0 讨论(0)
  • 2021-01-26 18:09

    You have to use array not object loop:

    foreach($inputs['test']['order'] as $test){           
            echo $test;
    
    }
    
    0 讨论(0)
  • 2021-01-26 18:22
    $myEcho = function($x){
        if(is_array($x)){foreach($x as $one){$myEcho($one);}
        }else{ echo $x; }
      };
    array_map($myEcho, $inputs['test']['order']);
    
    0 讨论(0)
  • 2021-01-26 18:27

    You use square braces [] to access array values, arrows -> to access properties on objects

    foreach($inputs['test']['order'] as $test){
            echo $test;
    }
    
    0 讨论(0)
  • 2021-01-26 18:29

    Simply use the helper method for Arr facade and avoid all these complications.

    For instance, if you've something like

    $array = ['products' => ['desk' => ['price' => 100]]];
    

    You can do this

    return Arr::get($array, 'products.desk.price');
    

    and it will return 100. The best part is if the key price doesn't exist, it doesn't throw and error.

    So, if the array had to be like this

    $array = ['products' => ['desk' => []];
    

    and you did this

    return Arr::get($array, 'products.desk.price');
    

    It would return null and not any error even though the item doesn't exist. You can also set a default value if you want like this

    return Arr::get($array, 'products.desk.price', 2);
    

    This would return 2 if the price doesn't exist. https://laravel.com/docs/8.x/helpers#method-array-get

    0 讨论(0)
提交回复
热议问题