Convert key to item with laravel collections

Viewed 166
[
  "bob" => $books
  "maria" => $otherBooks
]

to

[
  [
    name => "bob"
    data => $books
  ],
  [
    name => "maria"
    data =>  $otherBooks
  ]
]
2 Answers

You can utilize map, map takes $item and $key there is your input arrays key value, as the argument for the closure. If you map those to expected array structure this should work.

$result = collect([
  'bob' => $books
  'maria' => $otherBooks
])->map(function ($item, $key) {
    return [
        'name' => $key,
        'data' => $item,
    ]
});

You can do this easily with collections.

collect([
  "bob" => $books
  "maria" => $otherBooks
])->map(function ($books, $name) {
    return [
        'name' => $name,
        'data' => $books
    ];
});
Related