How to access nested array values

后端 未结 6 1808
轮回少年
轮回少年 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: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

提交回复
热议问题