我需要生成一个这样的数组:
$person = array(
array(
"name" => "brian",
"age" => "25"
),
array(
"name" => "simon",
"age" => "21"
)
);
我把这段代码放到一个简单的for循环中:
for ($x = 0; $x <= 10; $x++) {
$new_array = array("name"=>'Brian', "age"=>'25');
array_push($person, $new_array);
}
如果for循环必须重复10次,我应该有10行,Brian名称和25岁,但我有这个结果:
Array ( [1] => Array ( [name] => Brian [age] => 25 ) [value] => Array ( [name] => Brian [age] => 25 ) [0] => 0 [key] => 0 )
我是否在使用array_push做错了什么? 感谢
答案 0 :(得分:7)
创建$new_array = array();
for ($x = 0; $x <= 10; $x++) {
$new_array[] = array("name"=>'Brian', "age"=>'25');
}
print_r($new_array);
输出将是
Array ( [0] => Array ( [name] => Brian [age] => 25 )
[1] => Array ( [name] => Brian [age] => 25 )
[2] => Array ( [name] => Brian [age] => 25 )
[3] => Array ( [name] => Brian [age] => 25 )
[4] => Array ( [name] => Brian [age] => 25 )
[5] => Array ( [name] => Brian [age] => 25 )
[6] => Array ( [name] => Brian [age] => 25 )
[7] => Array ( [name] => Brian [age] => 25 )
[8] => Array ( [name] => Brian [age] => 25 )
[9] => Array ( [name] => Brian [age] => 25 )
[10] => Array ( [name] => Brian [age] => 25 )
)
答案 1 :(得分:0)
如果您已经将您的人员作为单个数组,那么array_push
可能会对您感兴趣,因为它允许您一步推送多个数组:
$brian = array(
"name" => "brian",
"age" => "25"
);
$simon = array(
"name" => "simon",
"age" => "21"
);
$persons = [];
array_push($persons, $brian, $simon);