开发者

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开发者_Go百科) "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?


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
}


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜