php array_map changes the first key to zero when it was originally one

浪子不回头ぞ 提交于 2019-12-11 06:14:49

问题


I have an array whick first key starts with one, and I need it like that.

//first iteration of $collections
$collections[1] = $data1;
$collections[2] = $data2;
...
//It does not have to start with zero for my own purposes

So I do the stuff needed like this:

//count($collections) = 56;
$collections = array_map(function($array)use($other_vars){
   //more stuff here

   //finally return:
   return $arr + ['newVariable'=$newVal];
},$collections);

When var_dump($collections); the first key is one, which is fine.

However, when I want to add another variable to the array like these:

//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);

Then if I iterate $collections again, it now starts at zero. Why? How can I make it start from 1 instead of zero in the first key? Any ideas?

So why is the first key changed to zero? How can I keep it to be one?

You can reproduce the problem by executing the following code (for example on php online):

$collections[1]=['data1'=>'value1'];
$collections[2]=['data2'=>'value2'];
$collections[3]=['data3'=>'value3'];
$collections[4]=['data4'=>'value4'];

$another[1]=['AnotherData'=>'AnotherVal1'];
$another[2]=['AnotherData'=>'AnotherVal2'];
$another[3]=['AnotherData'=>'AnotherVal3'];
$another[4]=['AnotherData'=>'AnotherVal4'];

var_dump($collections);
echo '<hr>';
var_dump($another);

echo '<hr>';

$grandcollection=array_map(function($a){
    return $a + ['More'=>'datavalues'];
},$collections);

var_dump($grandcollection);

echo '<hr>';

$grandcollection2 = array_map(function($a,$b){
    return $a + ['More'=>'datavalues','yetMore'=>$b['AnotherData']];
},$collections,$another);

var_dump($grandcollection2);

Now adding the solution suggested by lerouche

echo '<hr>';
array_unshift($grandcollection2, null);
unset($grandcollection2[0]);
var_dump($grandcollection2);

It now does work as intended


回答1:


After your $collections has been created, unshift the array with a garbage value and then delete it:

array_unshift($collections, null);
unset($collections[0]);

This will shift everything down by one, moving the first real element to index 1.



来源:https://stackoverflow.com/questions/44036228/php-array-map-changes-the-first-key-to-zero-when-it-was-originally-one

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