2017-07-06 80 views
0

我有对象的数组这样如何将id设置为对象数组中的每个新数组?

[ 
    { 
     "name": "qwe", 
     "password": "qwe" 
    }, 
    { 
     "name": "qwe1", 
     "password": "qwe1" 
    } 
] 

我需要添加id每对“名”和“密码”的,它必须是这样的

[ 
    { 
     "name": "qwe", 
     "password": "qwe" 
     "id":"0" 
    }, 
    { 
     "name": "qwe1", 
     "password": "qwe1" 
     "id":"1" 
    } 
] 

我试图运动使用foreach

$users[] = array('name' => $name, 'password' => $password); 
    $i = 0; 
    foreach ($users as $key => $value, "id" => 0) { 
     $value['id'] = $i; 
     $i++; 
} 

我在PHP初学者阵列,帮助please.What我做错了什么?

+0

请告诉我现在的关键?的print_r($用户); – clearshot66

+0

你的foreach表达式中的',“id”=> 0'是怎么回事? –

+0

'$ i = 0; foreach($ users){ $ users [$ user] =“id”=> $ i; $ i ++; }' – clearshot66

回答

1

当您使用:foreach($array as $key => $value)遍历数组时,$value将是原始对象的副本。更改副本将不会影响原始数组。

您需要确保更新原始值。有两种方法可以做到这一点。

直接访问原始数组:

foreach ($users as $key => $value) { 
    // Access the original array directly 
    $users[$key]['id'] = $i; 
    $i++; 
} 

使用引用(该& - 符号):

foreach ($users as $key => &$value) { 
    // The & will make it a reference to the original value instead of a copy 
    $value['id'] = $i; 
    $i++; 
} 
+0

Thx非常! –

相关问题