The problem lies in your nested foreach loop, which iterates over the entire $data2 array for each element of the $data1 array. This results in a total of $data1 * $data2 iterations.
array_map(function($v1, $v2){ echo $v1 . "<br>"; echo $v2 . "<strong><br><br></strong>"; }, $data1, $data2 /* , Add more arrays if needed manually */);
$it = new MultipleIterator(); $it->attachIterator(new ArrayIterator($data1)); $it->attachIterator(new ArrayIterator($data2)); //Add more arrays if needed foreach($it as $a) { echo $a[0] . "<br>"; echo $a[1] . "<strong><br><br></strong>"; }
$keysOne = array_keys($data1); $keysTwo = array_keys($data2); $min = min(count($data1), count($data2)); for($i = 0; $i < $min; $i++) { echo $data1[$keysOne[$i]] . "<br>"; echo $data2[$keysTwo[$i]] . "<strong><br><br></strong>"; }
foreach(array_combine($data1, $data2) as $d1 => $d2) { echo $d1 . "<br>"; echo $d2 . "<strong><br><br></strong>"; }
$func = function(...$numbers){ foreach($numbers as $v) echo $v . "<br>"; echo "<strong><br></strong>"; }; call_user_func_array("array_map", [$func, $data1, $data2]);
The above is the detailed content of How Can I Efficiently Iterate Through Two Arrays Simultaneously in PHP?. For more information, please follow other related articles on the PHP Chinese website!