php array_map最初将第一个键更改为零 [英] php array_map changes the first key to zero when it was originally one

查看:216
本文介绍了php array_map最初将第一个键更改为零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组,其中第一个键以一个开头,并且我需要这样。

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

var_dump($ collections);

但是,当我想向数组中添加另一个变量时,如下所示:

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

然后,如果我再次迭代$ collections,它现在从零开始。为什么?如何在第一个键中使其从1开始而不是0?
有什么想法吗?

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?

您可以通过执行以下代码来重现该问题(例如在php在线上):

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

现在可以按预期运行

推荐答案

在创建 $ collections 之后,用无用值取消移动数组,然后将其删除:

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

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

这会将所有内容向下移动一个,将第一个实数元素移至索引1。

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

这篇关于php array_map最初将第一个键更改为零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆