我很難嘗試更新數組中的值。我舉了一個簡單的例子來說明這個問題:數組包含玩家的名字和他們擁有的點數。每一輪之後,我想更新自己的點是這樣的:php:如何通過鍵更新關聯數組中的值
(沒有工作)
$players = array (
array (
"id" => 0,
"name" => "John",
"points" => 0
),
array (
"id" => 1,
"name" => "Chris",
"points" => 0
),
array (
"id" => 2,
"name" => "Peter",
"points" => 0
),
array (
"id" => 3,
"name" => "Greg",
"points" => 0
),
);
$points0 = 10;
$points1 = 20;
$points2 = 30;
$points3 = 40;
$i = 0;
foreach ($players as $player) {
if ($player["id"] == $i) {
$player["points"] = ${"points".$i};
} $i++;
}
var_dump($players);
必須是愚蠢的東西,但我一直在努力了幾個小時,我只是無法找到它。
感謝您的幫助!
你調試你的代碼?檢查壓縮和賦值之間的區別[運營商](http://php.net/manual/en/language.operators.php) – hassan
'$ player [「points」] == $ {「points」。$ i} ;'你在這裏比較,你想分配我相信'$ player [「points」] = $ {「points」。$ i};' - 編輯:* FIrst in * ;-) –
你可能想要使用點數組。 '$ points [0] = 10; $ points [1] = 20;'等等然後你可以做foreach($ player作爲$ player){$ player ['points'] = $ points [$ player ['id 「]]; }' – mkaatman