Doomish
Doomish

Reputation: 91

How to access the array inside the array

I don't know why I can't figure this out.

In my controller, how can I loop through this array and only get the values for name and url. both of those values will be passed to insert a new record.

array:3 [▼
  0 => array:2 [▼
    "name" => "Discogs"
    "url" => "https://www.discogs.com/artist/267549"
  ]
  1 => "2"
  2 => array:2 [▼
    "name" => "Official homepage"
    "url" => "http://www.blackmetal.com/~mega/TBD/"
  ]
]

Upvotes: 1

Views: 77

Answers (2)

Vlad Vladimir Hercules
Vlad Vladimir Hercules

Reputation: 1859

You can try utilising Laravel's collection for this...

$items = collect($array)
    ->filter(function($item) {
        return is_array($item);
    });

If you have extra attributes to the ones you listed then you can use map() to for this:

$items = collect($array)
    ->filter(function($item) {
        return is_array($item);
    })
    ->map(function($item) {
         return Arr::only($item, [
             'name',
             'url',
         ];
    });

p.s. don't forget to add use Illuminate\Support\Arr; to use Arr

Upvotes: 0

Giacomo M
Giacomo M

Reputation: 4711

You can do with this code:

foreach ($array as $value) {
    if (is_array($value) && isset($value['name']) && isset($value['url'])) {
        // Do whatever you want
    }
}

Upvotes: 4

Related Questions