5

How to access three items at once in a loop?

 2 years ago
source link: https://www.codesd.com/item/how-to-access-three-items-at-once-in-a-loop.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

How to access three items at once in a loop?

advertisements

I am having an issue with slicing from an array within a loop. What I am trying to do is iterate through an array and for each day return 3 different sections from the array. So for example day one should return 0,1,2 day 2 should return 3,4,5 etc... I am using array_slice() and it works for the first iteration, but on subsequent iterations, it only returns an array with 1 item in it. Any help would be much appreciated!!

Here is what I currently have:

foreach ($days as $day) {
    $j = $j + 1;
    var_dump("j" . $j);
    $activities = array_slice($activities, $j, $number_of_activities);
    var_dump("day" . $day);
    var_dump($activities);
}

This is what is returned from var_dump...

string(2) "j1"
string(4) "day1"
array(3) {
  [0]=> int(1)
  [1]=> int(2)
  [2]=> int(3)
}
string(2) "j2"
string(4) "day2"
array(1) {
  [0]=> int(3)
}


I think it's doing what it should. Your reassigning activities to the slice result. So on the second iteration the array has 3 elements, you're starting at index two, so your slice only has one element (the last). I think you have a logic error. You probably need a temporary variable to hold the slice instead of overwriting activities.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK