0

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?

5
  • My $status array can be whatever - I was trying to use it to be able to loop through the other arrays so whatever works... Commented Dec 28, 2011 at 13:30
  • Would your $a array also be print with those groups? Commented Dec 28, 2011 at 13:31
  • What correlation is there betweeh the $status array and $n/$p... I can't see any logical connection Commented Dec 28, 2011 at 13:31
  • The value in the status array (p) relates to the name of the other array ($p) so it is the name of the array, not the name of the array item. Commented Dec 28, 2011 at 13:36
  • @MarkBaker check my answer to found the logical connection Commented Dec 28, 2011 at 13:45

4 Answers 4

2

Use:

$arrayData=array('minutes','dollars','units');
foreach($arrayData as $data) {
    foreach($status as $value) {
       var_dump(${$value}[$data]);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

2
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

Comments

0

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.