简体   繁体   中英

Loop through multiple arrays with PHP

I have several arrays: $n , $p , $a

Each array is the same:

$n = array()
$n['minutes'] = a;
$n['dollars'] = b;
$n['units'] = c;

$p = array()
$p['minutes'] = x;
$p['dollars'] = y;
$p['units'] = z;

etc...

I also have a simple array like this:

$status = array('n', 'p', 'a');

Is it possible for me to use the $status array to loop through the other arrays?

Something like:

foreach($status as $key => $value) {
    //display the amounts amount here
};

So I would end up with:

a
x

b
y

c
z

Or, do I need to somehow merge all the arrays into one?

foreach($n as $key => $value) {
    foreach($status as $arrayVarName) (
        echo $$arrayVarName[$key],PHP_EOL;
    }
    echo PHP_EOL;
}

Will work as long as all the arrays defined in $status exist, and you have matching keys in $n, $p and $a

Updated to allow for $status

Use:

$arrayData=array('minutes','dollars','units');
foreach($arrayData as $data) {
    foreach($status as $value) {
       var_dump(${$value}[$data]);
    }
}

You could use next() in a while loop.

Example: http://ideone.com/NTIuJ

EDIT:

Unlike other answers this method works whether the keys match or not, even is the arrays are lists, not dictionaries.

If I understand your goal correctly, I'd start by putting each array p/n/... in an array:

$status = array();

$status['n'] = array();
$status['n']['minutes'] = a;
$status['n']['dollars'] = b;
$status['n']['units'] = c;


$status['p'] = array();
$status['p']['minutes'] = a;
$status['p']['dollars'] = b;
$status['p']['units'] = c;

Then you can read each array with:

foreach($status as $name => $values){
    echo 'Array '.$name.': <br />';
    echo 'Minutes: '.$values['minutes'].'<br />'; 
    echo 'Dollars: '.$values['dollars'].'<br />';
    echo 'Units: '.$values['units'].'<br />';
}

For more information, try googling Multidimensional 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