[英]php; Adding to the value of a multidimensional array in a loop
So I'm trying to make an array for stat growths in a fake rpg. 因此,我正在尝试为伪造的rpg创建一个统计数据增长数组。 It looks like this.
看起来像这样。
// base array
// $base: starting base stats
// $growth: growth rate per rng
$growths = array(
'HP' => array (70 => 20),
'STR' => array (50 => 7),
'MAG' => array (35 => 2),
'SKL' => array (45 => 6),
'SPD' => array (50 => 8),
'LCK' => array (55 => 5),
'DEF' => array (45 => 6),
'RES' => array (15 => 4),
);
//rng calculator
for ($x = 0; $x <= 20; $x++) {
foreach ($growths as $stat_name => $info) {
$roll = rand(0,100);
foreach ($info as $growth => $base) {
if ($roll <= $growth) {
$info[$growth] = ++$base;
print "(UP!) ";
}
echo "$stat_name: $base<br/ >";
}
}
}
My only issue is that the new $base
value after the rng calculator
refuses to store in the original array. 我唯一的问题是
rng calculator
拒绝存储在原始数组后的新$base
值。 Am I doing something wrong, or do I just need to rebuild the array from scratch and try something else? 我是在做错什么,还是只需要从头开始重建阵列并尝试其他操作? Any help would be appreciated!
任何帮助,将不胜感激!
In your first foreach loop, you assign the key of $growths
to $stat_name
and the value to $info
. 在你的第一个foreach循环,分配的关键
$growths
至$stat_name
和价值$info
。 These are temporary variables. 这些是临时变量。 If you change them, the original array is not affected.
如果更改它们,则原始阵列不受影响。
// This won't work because $info is temporary.
$info[$growth] = ++$base;
Instead, simply refer to the original array: 相反,只需引用原始数组即可:
// Do this instead.
$growths[$stat_name][$growth] = ++$base;
use reference 使用参考
just use foreach ($growths as $stat_name => &$info)
to replace conrresponding line in your code. 只需使用
foreach ($growths as $stat_name => &$info)
来替换代码中的相应行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.