foreach循环访问每个嵌套数组行

时间:2018-03-09 01:27:59

标签: php html arrays

我需要将以下数组值回显到表中,但只能获得第一行的正确输出[0]

循环遍历嵌套数组中每一行的语法是什么。当我简单地回显$ days时,它将两个值并排放在同一个

循环php

    foreach($inputs['course_details']['course_name'] as $courses){ 
    echo "<tr>";
    echo "<tr><td>" . $courses . "</td></tr>";
    echo "<td>Days and Times</td>";
    echo "<td>";
    foreach($inputs['course_details']['days_times'] as $days){

            echo $days[0];

    }
    echo "</td>";
    echo "</tr>";   
    };


"course_details" => array:9 [▼
"days_times" => array:9 [▼
  "monday" => array:2 [▼
    0 => 0
    1 => 1
  ]
  "tuesday" => array:2 [▼
    0 => 0
    1 => 1
  ]
  "wednesday" => array:2 [▼
    0 => 0
    1 => 1
  ]
  "thursday" => array:2 [▼
    0 => 0
    1 => 0
  ]
  "friday" => array:2 [▼
    0 => 0
    1 => 0
  ]
  "saturday" => array:2 [▼
    0 => 1
    1 => 0
  ]
  "sunday" => array:2 [▼
    0 => 1
    1 => 0
  ]
  "start_time" => array:2 [▼
    0 => "00:00:00"
    1 => "11:00:00"
  ]
  "end_time" => array:2 [▼
    0 => "17:00:00"
    1 => "14:00:00"
  ]
"course_name" => array:2 [▼
    0 => "Course 1"
    1 => "Course 2"
   ]
]

给我以下内容:

Course 1
Days and Times  0000011 00:00:00 17:00:00

Course 2
Days and Times  0000011 00:00:00 17:00:00

如何遍历数组中的每一行值?

1 个答案:

答案 0 :(得分:0)

您需要使$days[0]动态或更改每次运行。第一次运行时,您希望它保持原样,但您希望第二次$days[1],第三次$days[2],等等。

最简单的方法是在foreach循环中添加$key变量。第一次密钥为0,第二次密钥为1等。

要实现此目的,只需使用以下代码:

foreach($inputs['course_details']['course_name'] as $key => $courses){ 
  echo "<tr>";
  echo "<tr><td>" . $courses . "</td></tr>";
  echo "<td>Days and Times</td>";
  echo "<td>";
  foreach($inputs['course_details']['days_times'] as $days){
    echo $days[$key];
  }
  echo "</td>";
  echo "</tr>";   
};