array_merge changes the keys

雨燕双飞 提交于 2020-01-03 09:10:10

问题


I got the following array:

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

The problem is that, when I use array_merge( (array) "Select the data", $arr);, it does change the array keys into:

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

Is that possible to skip the array_merge key preversion so the output would look like this?

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

回答1:


Use the + operator to create a union of the 2 arrays:

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

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

var_dump($result);

Result:

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


来源:https://stackoverflow.com/questions/12397563/array-merge-changes-the-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!