2017-07-06 78 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非常! –

相關問題