使用 for 循环将数据推送到数组中

Push data into array with for loop

提问人:simo93bs 提问时间:7/18/2017 最后编辑:nerdlyistsimo93bs 更新时间:7/18/2017 访问量:17092

问:

我需要生成一个这样的数组:

$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做错了什么吗? 谢谢

PHP 数组 for 循环

评论

0赞 mickmackusa 9/25/2023
无法重现:3v4l.org/XZGOF

答:

12赞 Suneel Kumar 7/18/2017 #1

创造$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 ) 
)
0赞 user1915746 7/18/2017 #2

如果您已经将人员作为单个数组,那么您可能会感兴趣,因为它允许您在一个步骤中推送多个数组:array_push

$brian = array(
                "name" => "brian",
                "age" => "25"
        );
$simon = array(
        "name" => "simon",
        "age" => "21"
);

$persons = [];
array_push($persons, $brian, $simon);