gpt4 book ai didi

php:如何通过键更新关联数组中的值

转载 作者:行者123 更新时间:2023-12-04 19:27:49 25 4
gpt4 key购买 nike

我很难尝试更新数组中的值。我做了一个简单的例子来说明这一点:数组包含玩家的名字和他们的分数。在每一轮之后,我想像这样更新他们的积分:

(不工作)

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

一定是一些愚蠢的东西,但我已经尝试了几个小时,我就是找不到。

感谢您的帮助!

最佳答案

您需要添加 reference$player:

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

关键部分是 foreach 语句中的 & 符号 &。没有它,您将不会记录对数组的任何更改。

关于php:如何通过键更新关联数组中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43280172/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com