【问题标题】:Php foreach multiple arrays with if condionphp foreach 具有 if 条件的多个数组
【发布时间】:2021-11-10 17:33:45
【问题描述】:

我正在尝试使用 if 条件对多个数组进行 foreach,我有 3 个数组,如下所示:

$contents = array('content1', 'content2', 'content3', 'content4');    
$types = array('pdf', 'pdf', 'txt', 'pdf');    
$links = array('link1', 'link2', 'link3');

foreach ($contents as $key => $value) {
            
            echo "$value<br>";
            
        if ($types[$key] == 'pdf') {
             echo "$links[$key]<br>";
        }

}

输出是这样的:
内容1
链接1
内容2
链接2
内容3
内容4

Links 数组有 3 个值,其他 4 个。 如果内容类型是 pdf,我想要使用链接值,如果不跳过。 我想要如下输出:

内容1
链接1
内容2
链接2
内容3
内容4
链接3

感谢您的帮助

【问题讨论】:

  • 你能改变数组的结构吗?如果是:您可以将其更改为多维数组。
  • 你放弃了吗???

标签: php if-statement foreach


【解决方案1】:

如果数组的长度不同,那么您将无法使用密钥。您可以使用另一个变量来跟踪$links 中所需的密钥,或者您可以每次提前$links 的指针:

foreach ($contents as $key => $value) {
    echo "$value<br>\n";
        
    if ($types[$key] == 'pdf') {
         echo current($links) . "<br>\n";
         next($links);
    }
}

【讨论】:

    【解决方案2】:

    在这种情况下,您需要向前跳过链接数组,以便通过添加 else 语句来完成。 试试这个代码

    $contents = array('content1', 'content2', 'content3', 'content4');
    $types = array('pdf', 'pdf', 'txt', 'pdf');
    $links = array('link1', 'link2', 'link3');
    
    $skip_links_array = 0;
    
    foreach ($contents as $key => $value) {
    
        echo "$value<br>";
    
        if ($types[$key] == 'pdf') {
            echo $links[$key + $skip_type]."<br>";
        }else{
            $skip_type--;
        }
    
    }
    

    Demo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多