You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何根据相同索引重组两个PHP数组生成指定结构新数组?

Solution for Combining PHP Array Elements by Index

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:

  • $a1 will be array('0' => 'abc', '1' => 'pqr')
  • $a2 will be array('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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:46:06