2017-05-17 66 views
1

我有一个数组whick第一个键以一个开始,我需要它那样。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开始而不是零开始? 任何想法?

那么为什么第一个键变为零?我怎样才能让它成为一个?

可以通过执行以下代码(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); 

现在加入建议的解决方案通过lerouche

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

它如预期现在没有工作

+1

'array_map()'忽略原始键,它只是处理值并返回结果数组。 – Barmar

+0

数组索引通常从0开始。 – Barmar

+0

可能有[如何更改数组键从1开始而不是0]的重复(http://stackoverflow.com/questions/5374202/how-to-change-the-array-键到启动从-1-代替-的-0) – mickmackusa

回答

1

创建$collections之后,不改变阵列用垃圾值,然后将其删除:

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

这将通过一个一切下移,移动第一实元件到索引1

相关问题