Reputation: 15335
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?
Upvotes: 0
Views: 1157
Reputation: 315
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.
Upvotes: 0
Reputation: 212402
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
Upvotes: 2
Reputation: 5659
Use:
$arrayData=array('minutes','dollars','units');
foreach($arrayData as $data) {
foreach($status as $value) {
var_dump(${$value}[$data]);
}
}
Upvotes: 2
Reputation: 21975
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.
Upvotes: 0