在for循环中排列数组

时间:2013-06-27 20:59:52

标签: php arrays sorting object

我有一个如下所示的数组:

array(
    0 => object //ticket,
    1 => object //user,
    2 => object //employee,
    3 => object //ticket,
    4 => object //user
    5 => object //ticket,
    6 => object //employee
);

通过此,您可以看到票证对象始终存在,而员工和用户对象都是可选的。我想做的是循环它们并像这样组织它们:

array(
    [0] => array(
        [0] => object //ticket,
        [1] => object //user,
        [2] => object //employee,
    )
)

我遇到的问题是因为用户和员工是可选的我不知道如何根据上述模型正确编制索引,因为我偶尔会遇到一个没有员工或用户的人(在它没有的情况下,我希望该索引为null)。有什么想法吗?

编辑: 例如:

for ($i = 0; $i < count($result); $i++) {
        if ($result[$i] instanceof Ticket) {
            continue;
        } else {
            $newResult[$i][] = $result[$i]; //maybe I'm brainfarting, but cannot figure how to identify the last ticket index
        }
    }

3 个答案:

答案 0 :(得分:1)

这与您自己的答案类似,但完成后无需重新编制索引$newResult

$newIndex = -1;
$newResult = array();
foreach ($result as $object) {
    if ($object instanceof Ticket) {
        $newResult[] = array($object);
        $newIndex++;
    } else {
        $newResult[$newIndex][] = $object;
    }
}

但是,您的原始问题提到将子数组的未使用元素设置为null。你的答案没有那么做,所以我也没有。

答案 1 :(得分:0)

您可以使用 instanceof 检查哪个类'实例当前数组元素,然后根据需要对其进行分组:)

实施例

if( $array[0] instanceof ticket ) {
    // do some magic in here
}

http://php.net/manual/en/internals2.opcodes.instanceof.php

答案 2 :(得分:0)

是的,我绝对是聪明的。很抱歉浪费任何时间,这是循环:

$lastTicketIndex = 0;
    for ($i = 0; $i < count($result) - 1; $i++) {
        if ($result[$i] instanceof Ticket) {
            $newResult[$i][] = $result[$i];
            $lastTicketIndex = $i;
            continue;
        } else {
            $newResult[$lastTicketIndex][] = $result[$i];
        }
    }