简体   繁体   中英

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. 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. 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 . 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM