在php中打印每个值后,回显嵌套数组的数据并中断嵌套数组?

时间:2018-11-20 17:39:04

标签: php arrays multidimensional-array

我有3个foreach循环,想打印嵌套的第三个循环的值,但想在每个值都回显后中断嵌套的第三个循环。

例如。

foreach($res1 as $value1){
  foreach($value1 as $value2){
    foreach($value3 as $value4){
      echo $value4;  // here i am getting value like: 012345
    }
  }
}

方法是,我将得到012345的值,但我想在下一个td中打印0、1、2、3、4、5。

您可以检查出现问题的链接: https://www.chiczestuat.shop/product/signature-3-piece-owl-bracelet-limited-edition/

单击此链接向下滚动,您会发现。

enter image description here

希望您能理解。 谢谢

1 个答案:

答案 0 :(得分:0)

使用break;停止循环。

$res1 = [0 =>[0 => range(1,5), 1], 1];
foreach($res1 as $value1){
  foreach($value1 as $value2){
    foreach($value2 as $value4){
      echo $value4;  // here i am getting value like: 012345
    }
    break;
  }
  break;
}

示例:
https://3v4l.org/0epKY
我添加了一个var_dump来显示数组的外观。


创建临时数组的另一种方法,该临时数组用于通过key()“挖掘”到数组中。

$res1 = [0 =>[0 => range(1,5), 1], 1];
$temp = $res1;
for($i=0;$i<2;$i++){
    $temp = $temp[key($temp)];
}

foreach($temp as $value4){
    echo $value4;  // here i am getting value like: 012345
}

https://3v4l.org/vURpf

我相信时间会很充裕,所以请选择一个您更容易阅读的版本。