开发者

PHP array syntax

I'm attempting to make an array of users with ids and data. Normally the data is received from a database, but here it's hard-coded. I'm trying to make the users array return an associative array with an id and an array of data. For some reason, the arrays accessed with 'data' have no elements instead of each containing 5 and 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;
}

How can I ge开发者_Python百科t the inner arrays to add in the data?


The foreach loop is creating copies of your sub-arrays, and so the changes made inside the loop do not persist. Add an ampersand to make $user_row reference the originals instead of making copies:

foreach( $users as &$user_row )


Either change your loop to

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

to create the $user_row as references back to the original array elements, or

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


$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 operates on a copy of the array, adding element inside it won't do anything. use this instead: for ($i = 0; $i < count($users); $i++) {...}


Unfortunately your version of PHP copies instead of references $user_row try

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜