array_merge更改键

时间:2012-09-12 23:45:55

标签: php arrays array-merge

我得到了以下数组:

$arr = array(6 => 'Somedata', 7 => 'Somedata1', 8 => 'Somedata2');

问题是,当我使用array_merge( (array) "Select the data", $arr);时,它会将数组键更改为:

Array
(
    [0] => Not specified
    [1] => Somedata
    [2] => Somedata1
    [3] => Somedata2
)

是否可以跳过array_merge键preversion,以便输出看起来像这样?

Array
(
    [0] => Not specified
    [6] => Somedata
    [7] => Somedata1
    [8] => Somedata2
)

1 个答案:

答案 0 :(得分:8)

使用+ operator创建2个数组的并集:

$arr = array(6 => 'Somedata', 7 => 'Somedata1', 8 => 'Somedata2');

$result = (array)'Select the data' + $arr;

var_dump($result);

结果:

array(4) {
  [0]=>
  string(15) "Select the data"
  [6]=>
  string(8) "Somedata"
  [7]=>
  string(9) "Somedata1"
  [8]=>
  string(9) "Somedata2"
}