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);
它如預期現在沒有工作
'array_map()'忽略原始鍵,它只是處理值並返回結果數組。 – Barmar
數組索引通常從0開始。 – Barmar
可能有[如何更改數組鍵從1開始而不是0]的重複(http://stackoverflow.com/questions/5374202/how-to-change-the-array-鍵到啓動從-1-代替-的-0) – mickmackusa