0
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?

6
  • Looks like PHP? Which data do you want to iterate over? What is the result you want to get? Commented Jul 29, 2011 at 13:58
  • ya..its php i want to get each and every value in this array Commented Jul 29, 2011 at 13:59
  • i want somethin like 'Edit' -> 'ajax'. Commented Jul 29, 2011 at 14:00
  • With recursive function? Which contains a foreach . Commented Jul 29, 2011 at 14:01
  • What's the exact end result you want? You can loop over this array in an infinite numbers of ways. Are you saying each key in names is associated with the corresponding key in action? What should the result be then? A new array? Just echo the values? Commented Jul 29, 2011 at 14:03

3 Answers 3

3

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
}
Sign up to request clarification or add additional context in comments.

Comments

2
$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']);

Comments

0

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
    }
}

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.