In PHP, what is quickest way to turn the following array variables:
$id = [11,12,13];
$code = ['1234','5678','9012'];
$qty = [3,4,5];
$amount = [12.34,23.45,34.56];
Into an array of associative arrays, like the following:
[
['id'=>11,'code'=>'1234','qty'=>3,'amount'=>12.34],
['id'=>12,'code'=>'5678','qty'=>4,'amount'=>23.45],
['id'=>13,'code'=>'9012','qty'=>5,'amount'=>34.56],
]
Currently, I’m doing the following to convert the data.
$max = count($id);
$data = [];
for ($i=0; $i<$max; $i++) {
$data[] = [
'id' => $id[$i],
'code' => $code[$i],
'qty' => $qty[$i],
'amount' => $amount[$i]
];
}
My application does this a lot, and looking if there are ways to decrease processing time.
Currently using PHP version 5.6
3
Answers
My below code will optimize the loop by reducing the loop execution to half and will gives your expected result.
Demo Link
you can use foreach as well. I am not sure it will more efficient way but it can help you.
foreach
is typically the fastest method of the “general” approaches used to accomplish your desired end-results. This is due to thecount()
call prior to issuingfor()
accompanied with an incremental variable to determine the size and placement of the array to iterate over.Benchmarks: https://3v4l.org/ejIl5
Benchmark
1-5000
https://3v4l.org/IOlAmarray_map
was the slowestAs an added bonus from the “general” approaches, I also ran a benchmark of an optimized version of the double-ended iteration approach (
for ($i=0; $i<ceil($max/2); $i++)
). https://3v4l.org/KHUul and1-5000
https://3v4l.org/Mg95n which had wildly different values with the smaller array sizes, ranging from0.00030208 seconds
to0.00000095 seconds
, but on average was slower than the generalfor()
loop.