0

Consider the following:

$dropdown = array (
    "unitofmeasure" => array (
        "m"     => "meters",
        "ft"    => "feet"
    ),
    "facing_direction" => array (
        "0"     => array ("West","North-West","North","North-East","East","South-East"),
        "1"     => array("South","South-West")
    )
    .... 
)

Assume there are n number of sub arrays, not just the two shown above.

Iteration solution:

foreach($dropdown as $key => $val) {
    foreach($val as $k => $v) { 
        foreach($v as $id => $value) {
           //manipulate values here
        }
    }
}

My question is:

is there not a more elegant solution available in PHP?
for example something like foreach($dropdown->children()->children() ...)

I know there are a few semi-similar questions on SO but they're slightly different and the answers are mediocre.

3 Answers 3

1

Yes, I personally tend to use array_walk_recursive with a closure(if you're using PHP above 5.3).

You can, obviously, also use recursion if you like getting your hands dirty.

I suppose an example is in order:

$array = [ 0 => [0 => [ 0 => 1 ...]]];

$manipulated_array = [];

array_walk_recursive($array, function($value) use (&$manipulated_array)
{
  // do whatever you wish here
});
Sign up to request clarification or add additional context in comments.

2 Comments

RecursiveArrayIterator would also be an option.
Good call, forgot about that one. Another option would be RecursiveIteratorIterator - which has a silly name.
1

foreach() just expects an array, so if you only need to iterate ONE of those deeply nested arrays, then you can quite easily have

foreach($arr['level1']['level2'][...]['levelGazillion'] as ...)

Comments

0

I tend to use recursion in these situations:

function modify_array(&$arr)
{
    if (is_array(arr)) {
        foreach($arr as &$val) {
            modify_array($val);
        }
    } else {
        modify_value($arr);
    }
}

where modify_value(&$val) is whatever you want to do to each non-array child at any arbitrary depth

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.