Search code examples
phparrayslaravelobjectlaravel-5

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


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?


Solution

  • I think the best way is to combine zip method with transform or map:

    $names = [0 => 'name1', 1 => 'name2'];
    $classes = [0 => 'class1', 1 => 'class2'];
    
    $merged = collect($names)->zip($classes)->transform(function ($values) {
        return [
            'name' => $values[0],
            'class' => $values[1],
        ];
    });
    
    dd($merged->all());
    

    As a result you get array:

    array:2 [▼
      0 => array:2 [▼
        "name" => "name1"
        "class" => "class1"
      ]
      1 => array:2 [▼
        "name" => "name2"
        "class" => "class2"
      ]
    ]
    

    so if you need json, you can just use json_encode($merged)