PHP/Laravel – Create an array of objects from two simple arrays or an associative array that combines that two

arrayslaravellaravel-5objectPHP

I'm looking for a way transform a php associative array into an array of object and keying each association. I could also treat this as two separate simple arrays, one with the names and one with the classes. Here's an associative example…

array:2 [
  "someName" => "someClass"
  "someOtherName" => "someOtherClass"
]

Or

names => [0 => 'name1', 1 => 'name2']
classes => [0 => 'class1', 1 => 'class2']

…either way, I'm looking for an end result like this:

[
    { 'name': 'someName', 'class': 'someClass' },
    { 'name': 'someOtherName', 'class': 'someOtherClass' }
]

What's the smartest way to do this?

Best Answer

This output is the same on your first block.

$array = ['someName' => 'someClass', 'someOtherName'  => 'someOtherClass'];

You can also use laravel collections, provides a fluent, convenient wrapper for working with arrays of data. For example, check out the following code.

$collection = collect([
    'names' => [
         ['0' => 'name1', '1' => 'name2'],
     ],
    'classes' => [
         ['0' => 'class1', '2' => 'class2']
     ],
]);

There is also method combine that your looking for, The combine method combines the values of the collection, as keys, with the values of another array or collection: Read more info at https://laravel.com/docs/5.7/collections