请不要生气,因为我知道这是重复的问题!
我需要使用for循环将新元素添加到数组,因为我需要增加一些值才能带来新索引。
$array = [['first'=>'a', 'second'=>'b', 'third'=>'c'], ['first'=>'d', 'second'=>'e', 'third'=>'f'],['first'=>'g', 'second'=>'h', 'third'=>'i'] ];
$length = count($array);
for($i=1; $i<=$length; $i++){
array_push($array, ["number"=>$i]);
}
var_dump($array);
和var_dump显示:
array (size=6)
0 =>
array (size=3)
'first' => string 'a' (length=1)
'second' => string 'b' (length=1)
'third' => string 'c' (length=1)
1 =>
array (size=3)
'first' => string 'd' (length=1)
'second' => string 'e' (length=1)
'third' => string 'f' (length=1)
2 =>
array (size=3)
'first' => string 'g' (length=1)
'second' => string 'h' (length=1)
'third' => string 'i' (length=1)
3 =>
array (size=1)
'number' => int 1
4 =>
array (size=1)
'number' => int 2
5 =>
array (size=1)
'number' => int 3
array(size=6)
,我只需要array(size=3)
。
我需要在现有'number' => int 1
'number' => int 2
,'number' => int 3
,$array
谢谢!
答案 0 :(得分:0)
您可以使用:
$array = [['first'=>'a', 'second'=>'b', 'third'=>'c'], ['first'=>'d', 'second'=>'e', 'third'=>'f'],['first'=>'g', 'second'=>'h', 'third'=>'i'] ];
$length = count($array);
foreach($array as $k=>$v){
$array[$k]['number']=$k+1;
}
var_dump($array);
输出:
array(3) {
[0]=>
array(4) {
["first"]=>
string(1) "a"
["second"]=>
string(1) "b"
["third"]=>
string(1) "c"
["number"]=>
int(1)
}
[1]=>
array(4) {
["first"]=>
string(1) "d"
["second"]=>
string(1) "e"
["third"]=>
string(1) "f"
["number"]=>
int(2)
}
[2]=>
array(4) {
["first"]=>
string(1) "g"
["second"]=>
string(1) "h"
["third"]=>
string(1) "i"
["number"]=>
int(3)
}
}