简体   繁体   中英

How can I retrieve data from an array, 3 at a time?

Is there a better way in PHP to access this array in groups of three?

Let's say my array is a comma separated string like:

("Thora","Birch","Herself","Franklin Delano","Roosevelt","Himself (archive footage)","Martin Luther","King","Himself (archive footage) (uncredited)")

Although the array can end up being much larger, each one will be different but still in logical groups of three (firstname, lastname, role).

What I'm trying to accomplish is looping through the array in groups of three, so that the first record would have firstname[0]=>"Thora", lastname[0]=>"Birch" and role[0]=>"Herself".

I'm only used to foreach loops but don't see an extra parameter like "for each 3" so maybe someone can shed some light?

PHP has a function called array_chunk designed for this task.

Try this:

$sets = array_chunk($people, 3);
foreach ($sets as $set) {
  //you could use the following line to put each field into a nice variable
  list ($firstname, $lastName, $role) = $set;

  //if all you want to do is collect the values, do this 
  $firstNames[] = $set[0];
  $lastNames[] = $set[1];
  $role[] = $set[2];
}

Note that the last chunk might not be of size 3, so you should check that keys 1 and 2 are set with isset, if you can't guarantee that your array is always a multiple of 3 in length.

You can use a for -loop for this, assuming your 'people' array has a length of 3n .

$people = array("Thora","Birch","Herself","Franklin Delano","Roosevelt","Himself (archive footage)","Martin Luther","King","Himself (archive footage) (uncredited)");
$firstName = array();
$lastName = array();
$role = array();
for($i=0; $i<count($people); $i += 3){
   $firstName[] = $people[$i];
   $lastName[] = $people[$i+1];
   $role[] = $people[$i+2];
}

How about Pseudo code

for Index = 0 index = length index +=3
{
   Firstname= array[index]
   middlename = array[index+1]
   lastname = array[index+2]
   Do Something with them...
}

Alternatively, if you use PHP >= 5.3:

array_walk(
        range(1,9),//<== normally your array, range(1,9) is just an example/test value
        function($value,$key) use (&$return){
                 $return[$key % 3][] = $value;
        });
var_dump($return);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM