0

I have an object as below,

{"metaData":[{"name":"a"},{"name":"b"}],"rows":[[1,2],[3,4],[5,6]]}

I would like to change it to

[["a"=>1,"b"=>2],["a"=>4,"b"=>5],["a"=>5,"b"=>6]]

Is there any faster one liner that can convert this without going thru a loop in Laravel ?

1
  • 1
    Faster than what? Show us the code you've written. And by "faster", do you actually mean "faster to execute", or "uses fewer characters of source code", or "easier to read"? Commented Jun 8, 2022 at 14:07

1 Answer 1

3

You can get the keys with array_column, then map array_combine over the rows.

$keys = array_column($object->metaData, 'name');
$result = array_map(fn($row) => array_combine($keys, $row), $object->rows);

You could make it a one-liner like this, but it's more difficult to read, and it will call array_column for every row instead of just once.

$result = array_map(fn($row) => array_combine(array_column($object->metaData, 'name'), $row), $object->rows);

You need to be sure that each row is the same size as the metadata array or array_combine will fail. Based on the appearance of your object, it looks like this would probably always be true, but it's important to note.

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

1 Comment

Additional versions of the same advice: with array_walk() and with foreach()

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.