How to get values of multidimensional array using a loop

拟墨画扇 提交于 2020-01-05 12:15:11

问题


I have a multidimensional array:

$arr = Array (
            [0] => Array (
                [0] => 1001
                [1] => frank
                [2] => getfrankemail)
            [1] => Array (
                [0] => 1007
                [1] => youi
                [2] => getyouiemail)
            [2] => Array (
                [0] => 1006
                [1] => nashua
                [2] => getnashuaemail)
            );

I want to get the values of each array by using a loop or something so I could then put the values into variables such that $aff = 1001, $desc = frank and $camp = getfrankemail and so on...

Is there a way to achieve this? Thanks in advance!


回答1:


It depends on what you want to do with the variables but that should give you an idea.

$arr = Array (
            0 => Array (
                0 => 1001,
                1 => 'frank',
                2 => 'getfrankemail'),
            1 => Array (
                0 => 1007,
                1 => 'youi',
                2 => 'getyouiemail'),
            2 => Array (
                0 => 1006,
                1 => 'nashua',
                2 => 'getnashuaemail')
            );




foreach($arr as $array)
{
    foreach($array as $key => $info)
    {
      echo '<p>'.$key.' => '.$info.'</p>';
    }
}

Or

foreach($arr as $array)
{
    foreach($array as $info)
    {
      echo '<p>'.$info.'</p>';
    }
}

Or

foreach($arr as $array)
{
    echo '<p>'.$array[0].'</p>';
}

Or

foreach($arr[0] as $info)
{
    echo '<p>'.$info.'</p>';
}

And more...




回答2:


You can use a nested foreach loop (not very efficient or anything, but it gets the job done).

Here's an example:

foreach($arr as $key => $nested_arr){
    foreach($nested_arr as $key_2 => $value){
        //Do what you want with the values here. For example put them in 1d arrays.
    }
}


来源:https://stackoverflow.com/questions/20018643/how-to-get-values-of-multidimensional-array-using-a-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!