2

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?

2
  • You're looking for json_encode? Commented Oct 5, 2018 at 19:10
  • Nope. That's just return a json encoded string. Commented Oct 5, 2018 at 19:12

2 Answers 2

7

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)

Sign up to request clarification or add additional context in comments.

1 Comment

That's perfect! Thanks so much 😀
0

the simplest way to create object from array is

$array = [
    'id' => 'abc_123',
    'body' => 'how are you guys?'
];
$obj = json_decode(json_encode($comment));
$obj = (object) $array;

return $obj;

This will return the object of array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.