为什么有几个foreach循环不能一起工作?

时间:2018-06-18 08:05:02

标签: php

我写了这一行来读取三个数组并做了一些事情,但任何事情都没有在这三个foreach中运行!

foreach ($x_sort as $key => $x_name) {

    foreach ($y_sort as $key => $y_name){

        foreach ($z_sort as $key => $z_name){

            if ((!isset($y_name)) and (!isset($z_name)){
                echo $key . "." . $x_name . "," . "," . "<br>";

            }elseif ((isset($y_name)) and (!isset($z_name)){
                echo $key . "," . $x_name . "," . $key . ',' . $y_name . ',' . "<br>" ;
            }elseif ((!isset($y_name)) and (isset($z_name))){
                echo $key . "," . $x_name . ',' . ' ,' . $key . ',' . $z_name . "<br>" ;
            }elseif(isset($y_name)and isset($z_name))
            {
                echo $key . "," . $x_name . ',' . $key . ',' . $y_name . $key . ',' . $z_name . "<br>" ;
            }
        }
    }
}

2 个答案:

答案 0 :(得分:1)

代码中的循环解释存在轻微错误。

例如,

foreach ($x_sort as $key => $x_name) {

foreach ($y_sort as $key => $y_name){

这里两个for循环都是无关的。要使嵌套for循环成功迭代其元素,必须确保从顶层循环传播该值。

因此,您的代码将更改为

foreach ($x_sort as $key => $x_name) {

foreach ($x_name as $key1 => $y_name){

对第三个循环重复相同的过程。

答案 1 :(得分:0)

这里所有建议的解决方案仍然存在。我已修复所有语法错误,请查找所有(){}

<?php

foreach ($x_sort as $x_key => $x_name) {
    foreach ($y_sort as $y_key => $y_name) {
        foreach ($z_sort as $z_key => $z_name) {
            if (
                (!isset($y_name)) and
                (!isset($z_name))
            ) {
                echo $x_key . "." . $x_name . "," . "," . "<br>";
            } elseif (
                (isset($y_name)) and
                (!isset($z_name))
            ) {
                echo $x_key . "," . $x_name . "," . $y_key . ',' . $y_name . ',' . "<br>" ;
            } elseif (
                (!isset($y_name)) and
                (isset($z_name))
            ) {
                echo $x_key . "," . $x_name . ',' . ' ,' . $z_key . ',' . $z_name . "<br>" ;
            } elseif (
                (isset($y_name)) and
                (isset($z_name))
            ) {
                echo $x_key . "," . $x_name . ',' . $y_key . ',' . $y_name . $z_key . ',' . $z_name . "<br>" ;
            }
        }
    }
}