将两个数组合并为随机键索引,然后按键索引进行排序

时间:2018-01-04 12:30:31

标签: php arrays

假设你有这两个数组:

$a = array( 
  1 => 'This should be position #1 in merged array' 
);

$b = array( 
  0 => 'This should be position #0 in merged array',
  2 => 'This should be position #2 in merged array',
);

你怎么能得到一个看起来像这样的新数组:

$merged_a_b = array( 
  0 => 'This should be position #0 in merged array',
  1 => 'This should be position #1 in merged array',
  2 => 'This should be position #2 in merged array',
);

我尝试了array_merge( $a, $b ),但它更改了关键索引并导致了这个结果:

array (size=3)
  0 => string 'This should be position #0 in merged array' (length=42)
  1 => string 'This should be position #2 in merged array' (length=42)
  2 => string 'This should be position #1 in merged array' (length=42)

如您所见,值的顺序错误。

3 个答案:

答案 0 :(得分:3)

如果您需要保留密钥,可以使用array_replace()

$a = array( 
    1 => 'This should be position #1 in merged array' 
);
$b = array( 
    0 => 'This should be position #0 in merged array',
    2 => 'This should be position #2 in merged array',
);
array_replace($a, $b);

然后使用ksort()按键排序:

ksort($a);

答案 1 :(得分:1)

您还可以使用+运算符,然后使用ksort函数:

$a = array( 
  1 => 'This should be position #1 in merged array' 
);

$b = array( 
  0 => 'This should be position #0 in merged array',
  2 => 'This should be position #2 in merged array',
);

$merged = $a + $b;
ksort($merged);

答案 2 :(得分:0)

您可以使用+=赋值运算符使用相同的变量来合并单个变量中的多个数组,如下所示。在您可以使用ksort函数重新排序数组键及其值之后。

$array = array( 
  1 => 'This should be position #1 in merged array' 
);
$array += array( 
  0 => 'This should be position #0 in merged array',
  2 => 'This should be position #2 in merged array',
);
ksort($array);