简体   繁体   中英

How to get values of multidimensional array using a loop

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!

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM