Foreach循环两个不相等的数组

时间:2016-02-11 13:44:54

标签: php

我知道如何像这样循环通过相同的数组

foreach( $codes as $index => $code ) {
   echo 'The Code is '.$code;
   echo 'The Name is '.$names[$index];
}

不确定如何遍历这两个数组,并且当两个数组都有不同数量的元素时仍然设法获取所有值。

$code = array(R9,R10,R11,R12);

$names = array(Robert,John,Steve,Joe,Eddie,Gotham);

1 个答案:

答案 0 :(得分:2)

  

...如何遍历这两个数组,并且当两个数组都有不同数量的元素时,仍设法获取所有值。

您可以使用for循环。

解决方案是:

  • 将最长数组的长度作为for循环的条件。
  • 使用array_key_exists()函数检查索引是否存在于特定数组中,并相应地显示该元素。

所以你的代码应该是这样的:

$code = array("R9","R10","R11","R12");
$names = array("Robert","John","Steve","Joe","Eddie","Gotham");

$maxLength = count($code) > count($names) ? count($code) : count($names);

for($i = 0; $i < $maxLength; ++$i){
    echo array_key_exists($i, $code) ? 'The Code is '. $code[$i] : "";
    echo array_key_exists($i, $names) ? ' The Name is '. $names[$i] : "";
    echo "<br />";
}

输出:

The Code is R9 The Name is Robert
The Code is R10 The Name is John
The Code is R11 The Name is Steve
The Code is R12 The Name is Joe
The Name is Eddie
The Name is Gotham