PHP数组语法

时间:2011-02-22 19:18:58

标签: php arrays

我正在尝试使用ID和数据创建一组用户。通常,数据是从数据库接收的,但这里是硬编码的。我正在尝试让users数组返回一个带有id和数据数组的关联数组。由于某种原因,使用'data'访问的数组没有元素,而不是每个包含5和6。

$users = array();
$users[] = array( "id" => 1, "data" => array() );
$users[] = array( "id" => 2, "data" => array() );
foreach( $users as $user_row ) {
    $user_row['data'] [] = 5;
    $user_row['data'] [] = 6;
}

如何在数据中添加内部数组?

5 个答案:

答案 0 :(得分:2)

将循环更改为

foreach( $users as &$user_row ) {
                   ^---

$user_row作为引用创建回原始数组元素,或

foreach( $users as $key => $user_row) {
       $users[$key]['data'][] = 5;
       ...
}

答案 1 :(得分:2)

foreach循环正在创建子数组的副本,因此循环内部所做的更改不会持久存在。添加&符号以使$user_row引用原件而不是复制:

foreach( $users as &$user_row )

答案 2 :(得分:1)

$users = array();
$users[] = array( "id" => 1, "data" => array() );
$users[] = array( "id" => 2, "data" => array() );
foreach( $users as $key => $user_row ) {
    $users[$key]['data'] [] = 5;
    $users[$key]['data'] [] = 6;
}

答案 3 :(得分:0)

不幸的是你的PHP副本版本而不是引用$user_row 尝试

foreach( $users as &$user_row ) {
    $user_row['data'] [] = 5;
    $user_row['data'] [] = 6;
}

答案 4 :(得分:0)

foreach对数组的副本进行操作,在其中添加元素将不会执行任何操作。请改用:for ($i = 0; $i < count($users); $i++) {...}