如何在PHP数组/ JSON对象中打印第n个元素?

时间:2022-12-07 21:42:33

I have some foreach loops because of a multidimensional array/JSON object. I am trying to print every nth element (5th element in this case) of the last foreach loop. I tried using modulus but wasn't successful.

由于多维数组/ JSON对象,我有一些foreach循环。我正在尝试打印最后一个foreach循环的每个第n个元素(在本例中为第5个元素)。我尝试使用模数,但没有成功。

foreach($data['data'] as $k1=>$v1) {
 foreach($v1['cars'] as $k2=>$v2) {
  $counter= 1
   foreach($v2['colours'] as $k3=>$v3) {


        if ($counter % 5 == 0) {
      print $v3; //print every 5th colour
      $counter++;
      }


    }
   }  
  }

2 个解决方案

#1


3  

Your counter needs to be outside the if statement

您的柜台需要在if语句之外

$counter = 1;
foreach($data['data'] as $k1=>$v1) {
   foreach($v1['cars'] as $k2=>$v2) {
      foreach($v2['colours'] as $k3=>$v3) {
         if ($counter % 5 == 0) {
            print $v3; //print every 5th colour

         }
         $counter++;
     }
  }  
}

The reason being that every time you execute the loop you want the counter to increment, rather than just incrementing when the condition is true

原因是每次执行循环时都希望计数器递增,而不是仅在条件为真时递增

#2


0  

I believe you can array_chunk $v2 on 5 and output only [0].

我相信你可以在5上使用array_chunk $ v2并仅输出[0]。

foreach($data['data'] as $k1=>$v1) {
 foreach($v1['cars'] as $k2=>$v2) {
   $temp = array_chunk($v2['colours'],5);
   foreach($temp as $val){
      echo $val[0];
   }
  }  
 }

This also iterates less than your method as it skips four out of five elements.

这也比你的方法迭代少,因为它跳过了五个元素中的四个。

Short demo of what my code does: https://3v4l.org/GbU2T

我的代码所做的简短演示:https://3v4l.org/GbU2T

#1


3  

Your counter needs to be outside the if statement

您的柜台需要在if语句之外

$counter = 1;
foreach($data['data'] as $k1=>$v1) {
   foreach($v1['cars'] as $k2=>$v2) {
      foreach($v2['colours'] as $k3=>$v3) {
         if ($counter % 5 == 0) {
            print $v3; //print every 5th colour

         }
         $counter++;
     }
  }  
}

The reason being that every time you execute the loop you want the counter to increment, rather than just incrementing when the condition is true

原因是每次执行循环时都希望计数器递增,而不是仅在条件为真时递增

#2


0  

I believe you can array_chunk $v2 on 5 and output only [0].

我相信你可以在5上使用array_chunk $ v2并仅输出[0]。

foreach($data['data'] as $k1=>$v1) {
 foreach($v1['cars'] as $k2=>$v2) {
   $temp = array_chunk($v2['colours'],5);
   foreach($temp as $val){
      echo $val[0];
   }
  }  
 }

This also iterates less than your method as it skips four out of five elements.

这也比你的方法迭代少,因为它跳过了五个元素中的四个。

Short demo of what my code does: https://3v4l.org/GbU2T

我的代码所做的简短演示:https://3v4l.org/GbU2T