PHP数组语法

问题描述:

我正在尝试使用ID和数据创建一个用户数组。通常情况下,数据是从数据库接收的,但在这里是硬编码的。我试图让用户数组返回一个id和数组数组的数组。出于某种原因,该阵列与“数据”访问已经没有任何元素,而不是每片含5和6PHP数组语法

$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; 
} 

我怎样才能获得内心阵列中添加数据?

foreach循环创建子副本数组,所以在循环内进行的更改不会持续。添加符号,使$user_row参考原件,而不是使副本:

foreach($users as &$user_row) 

$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; 
} 

无论你的循环改变

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

创建$user_row就像回到了原来的数组元素的引用,或

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

不幸的是你的PHP拷贝而不是引用$user_row 的版本试试

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

的foreach对数组的拷贝操作,增加里面的元素不会做任何事情。用这个代替:for ($i = 0; $i < count($users); $i++) {...}