将数组替换为二维数组中的数字

时间:2012-09-19 15:19:40

标签: php multidimensional-array

我有二维数组,我希望在第二个数组

的随机数上替换第二个二维数组
Array
(
    [1] => Array
        (
            [0] => 1
            [1] => 3
            [2] => 5
            [3] => 500
            [4] => 600
            [5] => 700
        )

    [2] => Array
        (
            [0] => 2
            [1] => 4
            [2] => 6
        )

)

我想要

 Array (
     [1] => 5 (<- random from first array)     
     [2] => 6 (<- random from second array)    
 )

我试着这样做:

foreach($variables as $key => $val) {
        $variables = str_replace($val, $val[array_rand($val)], $variables);
}

为什么它不起作用?

2 个答案:

答案 0 :(得分:2)

foreach($variables as $key => $val) {
        $variables[$key] = $val[array_rand($val)];
}

答案 1 :(得分:0)

foreach ($variables as &$var) {
     $var = array_rand($variables[$var]);
}