如何使用foreach循环2或多个数组?

时间:2018-03-15 15:05:40

标签: php arrays loops for-loop foreach

如何使用foreach()循环多个数组?或者如何在$looping上定义for()?我已经厌倦了在AND上使用foreach()逻辑。

这是我的代码:

<?php
$b=["a","b","c","d","5"];
$a=["1","3","4","5"];
foreach($a as $a && $b as $b) {
    echo $a.$b;
}

// AND logic Error

$tipe=trim(fgets(STDIN));
$post=trim(fgets(STDIN));
if($tipe == "1") {
    $url="http://example.com/api"
    $postdata="post_data={$post[$x]}";
}

for($x=0;$x<10;$x++) {
    $ch=curl_init();
    curl_setopt($ch, CURLOPT_URL,$url); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS,$postdata);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_exec($ch);
}
// $x not defined

2 个答案:

答案 0 :(得分:0)

$x未定义,因为执行是在第一个foreach循环中停止的。您不能像使用foreach一样使用foreach,但可以将其更改为:

$b = ["a","b","c","d","5"];
$a = ["1","3","4","5"];

foreach($a as $key => $value) {
    echo $value . $b[$key]; // just make sure to have at least the same number of elements in the $b array as the $a array has
}

然而,很难理解你想用这段代码实现什么目的以及它应该做什么。

答案 1 :(得分:0)

您必须首先获取数组值的最大数量,然后重复循环直到最大数量,希望对您有所帮助

$b=["a","b","c","d","5"];
$a=["1","3","4","5"];

$max = ( count($a) > count($b) ) ? count($a) : count($b);

for( $i=0 ; $i<$max; $i++){
  $strA = (isset($a[$i])) ? $a[$i] : '';
  $strB = (isset($b[$i])) ? $b[$i] : '';

  echo $strA . $strB;
}