0

I'm trying to pluck a value from a multidimensional (I think that's the term) array and append it to a string variable. It's a POST to Laravel from a JSON array.

The array:

0:
  icon: "nanny"
  name: "Nanny"
  order: 1
  price: 3000
  selected: true

1:
  icon: "driver"
  name: "Driver"
  order: 3
  price: 2000
  selected: true

I want to get the value of name and append it to a variable as a string.

$items = 'Nanny, Driver, '

This is my attempt

$items = '';

foreach($request->services as $service) {
    foreach ($service as $key => $value) {
        $items .= $key['name'] . ', ';
    }
}
Jack Barham
  • 3,197
  • 10
  • 41
  • 62
  • 1
    Seems like you can remove one of the foreach loops, like `$items = ''; foreach($request->services as $service) { $items .= $service['name']; }` – Steve T Dec 09 '18 at 18:59

1 Answers1

2

$key is the key, you want the value, and you only want the value for "name". Regardless, we can do this in one line:

$items = implode(', ', array_column($request->services, 'name'));
mpen
  • 272,448
  • 266
  • 850
  • 1,236
  • That's exactly what I need. Works perfectly. Thank you. – Jack Barham Dec 09 '18 at 18:59
  • 1
    FYI if using Laravel, it has a method called `pluck()` which does a similar job to `array_column()`: https://laravel.com/docs/5.7/collections#method-pluck – lufc Dec 09 '18 at 19:24