如何使用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
答案 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;
}