Rahul_2289
Rahul_2289

Reputation: 331

How to loop through a mulitdimensional array in php?

array(2) {
    ["names"]=> array(4) { 
        [0]=> string(4) "Edit" 
        [1]=> string(6) "Delete" 
        [2]=> string(8) "Activate" 
        [3]=> string(10) "Deactivate"
    } 
    ["action"]=> array(4) { 
        [0]=> string(4) "ajax" 
        [1]=> string(4) "abc" 
        [2]=> string(4) "def" 
        [3]=> string(4) "xyz" 
    } 
} 

How do i loop through this in a single foreach loop?

Upvotes: 0

Views: 142

Answers (3)

Yossi
Yossi

Reputation: 392

I guess the best way is a recursive function which can move through even three dimensions and more

function MoveThroughArray($arr)
{
    foreach($arr as $value)
    {
        if(is_array($value))
            MoveThroughArray($value);
        else
            // Do Something
    }
}

Upvotes: 0

Andreas Wong
Andreas Wong

Reputation: 60516

$newArr = array();
foreach($data['names'] as $i => $val) {
   $newArr[$val] = $data['actions'][$i];
}

Or if you want a one liner at that

$newArr = array_combine($data['names'], $data['action']);

Upvotes: 2

Felix Kling
Felix Kling

Reputation: 816424

Assuming both arrays are of the same size and have the same keys:

foreach($array['names'] as $k => $name) {
    $action = $array['actions'][$k];
    // do whatever you want to do with $name and $action
}

Upvotes: 3

Related Questions