1

我有一个多维数组,我想在应用函数后为每个数组创建新变量。我真的不知道如何将 foreach 与这种数组一起使用。到目前为止,这是我的代码:

$main_array = array
(
    [first_array] => array
        (
            ['first_array1'] => product1
            ['first_arrayN'] => productN
        )

    [nth_array] => Array
        (
            [nth_array1] => date1
            [nth_arrayN] => dateN
        )
)

function getresult($something){
        ## some code
        };

foreach ($main_array as ["{$X_array}"]["{$key}"] => $value) {
    $result["{$X_array}"]["{$key}"] = getresult($value);
    echo $result["{$X_array}"]["{$key}"];
    };

任何帮助,将不胜感激!

4

2 回答 2

3
foreach ($main_array as &$inner_array) {
    foreach ($inner_array as &$value) {
        $value = getresult($value);
        echo $value;
    }
}

unset($inner_array, $value);

Note the &, which makes the variable a reference and makes modifications reflect in the original array.

Note: The unset is recommended, since the references to the last values will stay around after the loops and may cause unexpected behavior if you're reusing the variables.

于 2012-09-14T15:45:27.110 回答
0
foreach($main_array AS $key=>$array){
    foreach($array AS $newKey=>$val){
        $array[$newKey] = getResult($val);
    }
   $main_array[$key] = $array;
}
于 2012-09-14T15:49:07.760 回答