Home > Mobile >  access values in nested array using Laravel array helpers
access values in nested array using Laravel array helpers

Time:12-18

I want to access the values for the element named name within the parent element named tags for this nested array:

$array = Post::whereIn('id', [1,2,3,4])->with('tags')->get()->toArray();

dd($array)

array:4 [▼
  0 => array:5 [▼
    "id" => 1
    "text" => "The First"
    "tags" => array:3 [▼
      0 => array:5 [▼
        "id" => 4
        "name" => "Tag 4"
        "pivot" => array:2 [▶]
      ]
      1 => array:5 [▼
        "id" => 4
        "name" => "Tag 4"
        "pivot" => array:2 [▶]
      ]
      2 => array:5 [▼
        "id" => 5
        "name" => "Tag 5"
        "pivot" => array:2 [▶]
      ]
    ]
  ]
  1 => array:5 [▼
    "id" => 2
    "text" => "The Second"
    "tags" => array:1 [▼
      0 => array:5 [▼
        "id" => 4
        "name" => "Tag 4"
        "pivot" => array:2 [▶]
      ]
    ]
  ]
  2 => array:5 [▶]
  3 => array:5 [▶]
]

I need the data inside of an array that looks something more like this:

        ['id' => '4','name' => 'Tag 4'],
        ['id' => '4','name' => 'Tag 4'],
        ['id' => '5','name' => 'Tag 5'],
        ['id' => '4','name' => 'Tag 4'],
  

I am currently attempting to:

use Illuminate\Support\Arr;

$tags = Arr::get($array, 'tags.name');

returns Null

I from here would then want to pick out the unique values to display them using the unique() method on the array that I am trying to obtain

CodePudding user response:

you can use in this way

foreach($array as $tag) {
$var =  $tag['tags'];
// or this way as well
$var1 = $tags = Arr::get($tag, 'tags.name');
}

CodePudding user response:

Edit:

If you are using PHP then I would make a foreach:

foreach($array->getTags() as $tag) {
  dd($tag);
}
  • Related