2016-02-11 22 views
1

我知道如何通过平等阵列循环这样的foreach循环两个不相等的阵列

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); 
+0

只是遍历他们separatly? – Qirel

+0

对..但那不是我想要做的。我想为这两个数组运行一个循环。感谢您尝试最好:) –

+0

您可能最好使用两个独立的循环,因为它们的长度不同。你可以使用一个循环作为最长的循环,然后用它循环遍历所有内容,并检查是否有更多的元素在较小的元素中(这样你就不会回显那些不在那里的东西)。 – Qirel

回答

2

...如何通过这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 
+0

谢谢你指导我正确的方向:) –

+0

@WaliHassan非常欢迎! :-) –