【问题标题】:How to Looping 2, or much array using foreach?如何使用 foreach 循环 2 或多个数组?
【发布时间】:2018-03-15 15:05:40
【问题描述】:

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

这是我的代码:

<?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

【问题讨论】:

标签: php arrays loops for-loop foreach


【解决方案1】:

$x 未定义,因为执行在您的第一个 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
}

但是,很难理解您究竟想用这段代码实现什么以及它应该做什么。

【讨论】:

  • 注意:数组到字符串的转换在 /storage/sdcard1/telegram.php 第 70 行 PHP 注意:数组到字符串的转换。 $postdata="chat_id={$cid}&photo={$jpg}&caption={$status}";我想在 $postdata 上循环 $jpg=array 和 $status=array
【解决方案2】:

您必须首先获取数组值的最大计数,然后迭代循环直到最大计数,我希望这会对您有所帮助

$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;
}

【讨论】:

    猜你喜欢
    • 2021-08-24
    • 1970-01-01
    • 2013-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多