简体   繁体   English

使用PHP遍历多个数组

[英]Loop through multiple arrays with PHP

I have several arrays: $n , $p , $a 我有几个数组: $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? 我可以使用$ status数组遍历其他数组吗?

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 只要$ status中定义的所有数组都存在,并且在$ n,$ p和$ a中具有匹配的键,就可以工作

Updated to allow for $status 已更新为允许$ 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. 您可以在while循环中使用next()

Example: http://ideone.com/NTIuJ 示例: 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: 如果我正确理解了您的目标,那么我将从将每个数组p / n / ...放入一个数组开始:

$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 . 有关更多信息,请尝试使用“ 多维数组”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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