如何从阵列中检索数据,一次3个?

时间:2010-10-06 14:25:09

标签: php arrays loops

有没有更好的方法在PHP中以三个为一组访问此数组?

假设我的数组是逗号分隔的字符串,如:

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

尽管数组最终会变得更大,但每个数组都会有所不同,但仍然是三个逻辑组(名字,姓氏,角色)。

我想要完成的是以三个为一组循环遍历数组,以便第一个记录具有firstname[0]=>"Thora", lastname[0]=>"Birch" and role[0]=>"Herself".

我只习惯foreach循环,但是没有看到像“每3个”这样的额外参数,所以也许有人可以解决这些问题?

4 个答案:

答案 0 :(得分:4)

PHP有一个名为array_chunk的函数,专门用于此任务。

试试这个:

$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];
}

请注意,最后一个块的大小可能不是3,因此如果无法保证数组的长度始终是3的倍数,则应检查键1和2是否设置为isset。

答案 1 :(得分:2)

您可以使用for - 循环,假设您的'people'数组的长度为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];
}

答案 2 :(得分:1)

怎么样 伪代码

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

答案 3 :(得分:1)

或者,如果您使用PHP&gt; = 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);