php array_map меняет первый ключ на ноль, когда он был изначально

У меня есть массив, в котором первый ключ начинается с единицы, и мне это нужно вот так.

//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_dump($collections); первый ключ один, что хорошо.

Однако, когда я хочу добавить другую переменную в массив, как эти:

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

Затем, если я повторю итерацию $ коллекций снова, теперь она начинается с нуля. Зачем? Как я могу сделать так, чтобы он начинался с 1 вместо нуля в первом ключе? Есть идеи?

Так почему же первый ключ изменен на ноль? Как я могу сохранить это, чтобы быть одним?

Вы можете воспроизвести проблему, выполнив следующий код ( например, на 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);

Теперь добавляем решение, предложенное Lerouche

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

Теперь он работает как задумано

1 ответ

Решение

После вашего $collections был создан, отмените массив со значением мусора и затем удалите его:

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

Это сместит все на единицу, переместив первый реальный элемент в индекс 1.

Другие вопросы по тегам