Mat
Mat

Reputation: 25

foreach and multidimensional array

I have a multidimensional array and I want to create new variables for each array after apllying a function. I dont really know how to use the foreach with this kind of array. Here's my code so far:

$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}"];
    };

Any help would be appreciated!

Upvotes: 1

Views: 102

Answers (2)

deceze
deceze

Reputation: 522081

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.

Upvotes: 3

Surace
Surace

Reputation: 711

foreach($main_array AS $key=>$array){
    foreach($array AS $newKey=>$val){
        $array[$newKey] = getResult($val);
    }
   $main_array[$key] = $array;
}

Upvotes: 0

Related Questions