如何根据相同索引重组两个PHP数组生成指定结构新数组?
Hey there! Let's get this sorted for you. Since you have two small arrays with fixed indices, the most straightforward way is to directly extract the elements you need and build your new arrays.
First, let's start with your original arrays:
$array1 = array('0' => 'abc', '1' => 'xyz'); $array2 = array('0' => 'pqr', '1' => 'mno');
Direct Approach (Perfect for Your Current Case)
You can manually construct the new arrays by picking the corresponding index elements from each original array:
$a1 = array( '0' => $array1[0], '1' => $array2[0] ); $a2 = array( '0' => $array1[1], '1' => $array2[1] );
This will give you exactly the result you're looking for:
$a1will bearray('0' => 'abc', '1' => 'pqr')$a2will bearray('0' => 'xyz', '1' => 'mno')
Scalable Approach (For Longer Arrays)
If you ever need to handle arrays with more elements (instead of just two), using a loop will save you from writing repetitive code. Here's how you can do it:
$a1 = []; $a2 = []; // Assuming both arrays have the same length foreach ($array1 as $index => $val) { $a1[$index] = $val; $a2[$index] = $array2[$index]; }
This way, no matter how many elements your original arrays have, the code will automatically build $a1 and $a2 by grouping elements from the same index across both arrays.
内容的提问来源于stack exchange,提问作者Mohd Hasan

