Ad

Laravel Pluck Value And Append Additional String

- 1 answer

I am getting the list of books through pluck

$outputArray = $list->pluck('title', 'id')->toArray();

so I have a list of all possible books. Then through $books_selected = $books->pluck('title', 'id')->toArray(); I have a selected books. In my output array I would like to appened True if the id is in $books_selected and false otherwise. Is there a way to do it?

Ad

Answer

One way would be to use Collections#map:

$outputArray = $list
  ->pluck('title', 'id')
  ->map(function ($title, $id) use ($books_selected) {
    return [$title, in_array($id, $books_selected)];
  });

Or in a shorter form if you're using PHP 7.4:

$outputArray = $list
  ->pluck('title', 'id')
  ->map(fn($title, $id) => [$title, in_array($id, $books_selected)]);

Your final array should be in this form:

[
  id1 => ['title1', true],
  id2 => ['title2', false],
  ...
]
Ad
source: stackoverflow.com
Ad