I have an array returned from a form as below:
[ticket_detail] => Array
(
[ticket_id] => Array
(
[0] => 101
[1] => 102
[2] => 103
)
[price] => Array
(
[0] => 10
[1] => 20
[2] => 30
)
)
I could extract a single column values using the below code:
$arr = array_map(function ($x) {
return $x[0];
}, $ticket_detail);
Array
(
[ticket_class_id] => 101
[price] => 10
}
How do I combine this with array_walk so I can get the below result?
[ticket_detail] => Array
(
[0] => Array
(
[ticket_id] => 101
[price] => 10
)
[1] => Array
(
[ticket_id] => 102
[price] => 20
)
[2] => Array
(
[ticket_id] => 103
[price] => 30
)
)
PS: I’m looking for an alternate solution without using a foreach
loop.
2
Answers
Here is the code to get your required result.
UPDATE
Here is the way to make it more dynamic
Ok, since you wish to make this generic, you can do the below.
Get the subarray keys like
ticket_id, price
etc since they need to be attached as keys for each resultant row usingarray_keys
.Get no. of rows for any individual subarray(any because the rows would be symmetric, as in same for every other key).
Use
array_walk
to walk over these column values one by one. Use them as index in yourarray_column
function on yourticket_detail
array and usearray_combine
to combine the initially retrieved keys(as done in the 1st step) with the current row data picked up from each individual subarray and add them to the result.Snippet:
Live Demo