如何在php中循环遍历多维数组?

时间:2011-07-29 13:57:03

标签: php arrays loops multidimensional-array

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

如何在单个foreach循环中循环执行此操作?

3 个答案:

答案 0 :(得分:3)

假设两个阵列的大小相同且密钥相同:

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

答案 1 :(得分:2)

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

或者如果你想在那个

上有一个班轮
$newArr = array_combine($data['names'], $data['action']);

答案 2 :(得分:0)

我想最好的方法是递归函数,它甚至可以在三个维度上移动

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