【问题标题】:array_merge changes the keysarray_merge 更改键
【发布时间】:2012-09-06 00:39:39
【问题描述】:

我得到了以下数组:

$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 密钥预版本使输出看起来像这样?

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

【问题讨论】:

  • 请给我们看代码。 array_mergepreserving keys by default
  • @EXQStudio 代码在我问题的第二行,后面有一个简单的array_merge( (array) "Select the data", $arr);,然后是print_r转储。
  • 为什么要将字符串转换为数组?为什么不Array("Select the data")
  • Array_merge 保留第一个数组的键,你不能得到你在切换数组后得到的结果吗:array_merge($arr, (array) "Select the data");
  • @EXQStudio 为什么不呢?请参阅php.net/manual/en/function.array-merge.php Example #1,它没有被禁止,并且工作正常。

标签: php arrays array-merge


【解决方案1】:

使用+ operator 创建两个数组的联合:

$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"
}

【讨论】:

  • 但要小心,如果它们的数组具有相同的键,这可能会覆盖数据。尝试使用$arr = array(0 => 'Somedata', 7 => 'Somedata1', 8 => 'Somedata2'); 作为输入运行它。
猜你喜欢
  • 2012-07-23
  • 1970-01-01
  • 2011-08-21
  • 1970-01-01
  • 2011-04-07
  • 1970-01-01
  • 2011-06-07
  • 1970-01-01
  • 2011-10-31
相关资源
最近更新 更多