php数组_映射将第一个键更改为零,而它原来是一个键
我有一个数组,第一个键以1开头,我需要这样的数组php数组_映射将第一个键更改为零,而它原来是一个键,php,arrays,array-map,Php,Arrays,Array Map,我有一个数组,第一个键以1开头,我需要这样的数组 //first iteration of $collections $collections[1] = $data1; $collections[2] = $data2; ... //It does not have to start with zero for my own purposes 所以我做了如下所需的工作: //count($collections) = 56; $collections = array_map(function(
//first iteration of $collections
$collections[1] = $data1;
$collections[2] = $data2;
...
//It does not have to start with zero for my own purposes
所以我做了如下所需的工作:
//count($collections) = 56;
$collections = array_map(function($array)use($other_vars){
//more stuff here
//finally return:
return $arr + ['newVariable'=$newVal];
},$collections);
当var\u转储($collections)时代码>第一个键是1,这很好
但是,当我想向数组中添加另一个变量时,如下所示:
//another array starting at one //count($anotherArray) = 56;
$anotherArray[] = ['more'=>'values'];
$collections = array_map(function($arr,$another)use($other_vars){
//more stuff here
//finally return:
return $arr + ['newVariable'=$newVal,'AnotherVar'=>$another['key']];
},$collections,$anotherArray);
然后,如果我再次迭代$collections,它现在从零开始。为什么?如何使第一个键从1开始而不是从零开始?
有什么想法吗
那么为什么第一个键变为零呢?我怎样才能保持一个呢
您可以通过执行以下代码()来重现问题:
$collections[1]=['data1'=>'value1'];
$collections[2]=['data2'=>'value2'];
$collections[3]=['data3'=>'value3'];
$collections[4]=['data4'=>'value4'];
$另一个[1]=['AnotherData'=>'AnotherVal1'];
$另一个[2]=['AnotherData'=>'AnotherVal2'];
$另一个[3]=['AnotherData'=>'AnotherVal3'];
$另一个[4]=['AnotherData'=>'AnotherVal4'];
var_dump($collections);
回声“
”;
var_dump(另一美元);
回声“
”;
$grandcollection=数组\映射(函数($a){
返回$a+['More'=>'datavalues'];
}(港币),;
var_dump($grandcollection);
回声“
”;
$grandcollection2=数组映射(函数($a,$b){
返回$a+['More'=>'datavalues','yetMore'=>$b['AnotherData']];
},$collections,$other);
var_dump($grandcollection2);
现在添加建议的解决方案
echo'
';
数组_unshift($grandcollection2,null);
未设置($grandcollection2[0]);
var_dump($grandcollection2);
它现在可以按预期工作在创建$collections
后,使用垃圾值取消移动数组,然后将其删除:
array_unshift($collections, null);
unset($collections[0]);
这会将所有元素下移1,将第一个实数元素移动到索引1。array\u map()
忽略原始键,它只处理值并返回结果数组。数组索引通常从0开始。可能重复
echo '<hr>';
array_unshift($grandcollection2, null);
unset($grandcollection2[0]);
var_dump($grandcollection2);
array_unshift($collections, null);
unset($collections[0]);