将多个对象插入到数组中

时间:2016-07-06 03:17:50

标签: php arrays

我试图将3个不同类的对象插入到数组中,这样,数组看起来就像这个[objA,.., objA, objB,.., objB, objC,..., objC]。 我设置函数的方法是获取一个rand多次objA,objB和objC将被插入到数组中,然后有3个for循环来插入每个对象。

    $no_of_objA = rand(5, 10);
    $no_of_objB = rand(1, 5);
    $no_of_objC = rand(3, 8);

    for($i = 0; $i < $no_of_objA; $i++)
        $this->users[$i] = new A();

    for($i = $no_of_objA; $i < ($no_of_objA + $no_of_objB); $i++)
        $this->users[$i] = new B();

    for($i = ($no_of_objA + $no_of_objB); $i < ($no_of_objA + $no_of_objB + $no_of_objC); $i++)
        $this->users[$i] = new C();

最坏的情况显然是由rand函数生成的最大数字的Big-O。 这很好,但是,我有点认为可能有一个更优雅和优化的解决方案来实现这一目标。

我并不关心插入对象的顺序......

1 个答案:

答案 0 :(得分:2)

如果您不关心使用ID跟踪

$a_count = mt_rand(5, 10); //Faster than rand
$b_count = mt_rand(1, 5);
$c_count = mt_rand(3, 8);

for($i = 0;$i < $a_count; $i++){
    $this->users[] = new A();
}
for($i = 0;$i < $b_count; $i++){
    $this->users[] = new B();
}
for($i = 0;$i < $c_count; $i++){
    $this->users[] = new C();
}
相关问题