我有一个名为emp_rec的数组,其中有100多个员工,每个员工有大约60个字段,我使用以下方法一次使用一个员工…
foreach($emp_rec as $obj) {
$name = $obj->get_empname();
//.....
......///
}
现在我计划在一个循环中一次使用三个雇员,我该怎么做呢?
你可以试试:
$current = Array();
while(($current[0] = array_shift($emp_rec))
&& ($current[1] = array_shift($emp_rec))
&& ($current[2] = array_shift($emp_rec))) {
// do stuff here
}
if( $current[0]) {
// there were records left over, optionally do something with them.
}
试试这样:
for ($i = 0; $i < count($emp_rec); $i+=3) {
$emp1 = $emp_rec[$i];
$emp2 = $emp_rec[$i+1];
$emp3 = $emp_rec[$i+2];
}
这里可以一次迭代相同的多个对象。很容易适应
<?php
// Example of class
class A {
public $a = 'a';
public $b = 'b';
public $c = 'c';
}
$obj1 = new A; // Instantiate 3 objects
$obj2 = new A;
$obj3 = new A;
$objs = array((array)$obj1, (array)$obj2, (array)$obj3); // Array of objects (cast in array)
foreach ($objs[0] as $key => $value) {
echo $objs[0][$key];
echo $objs[1][$key];
echo $objs[2][$key];
}
aaabbbccc
怎么样:
$GROUP_SIZE = 3;
$emp_count = count($emp_rec);
for ($i=0; $i<$emp_count; $i+=$GROUP_SIZE) {
for ($j=0; $i+$j<$emp_count && $j<$GROUP_SIZE; $j++) {
$current = $emp_rec[$i+$j];
$name = $current->get_empname();
}
}
如果您需要同时操作3个或N个员工,它会让您知道当前员工在哪个"组"。