在PHP中合并对象

时间:2015-03-05 22:01:31

标签: php arrays object

我有例如:

$onePack = $pack->findByCity('London'); //this return me 3 objects from class Pack
$twoPack = $pack->findByCity('New York'); //this return me 2 objects from class Pack
$threePack = $pack->findByCity('Los Angeles'); //this return me 5 objects from class Pack

我想将此对象合并到一个变量中,然后使用foreach。

我知道 - 我可以制作数组,例如:

$array = array();

和下一个:

foreach($onePack as $one) {
    $array[] = $one;
}
foreach($twoPack as $two) {
    $array[] = $two;
}
foreach($threePack as $three) {
    $array[] = $three;
}

现在我将所有对象(10)放在一个变量中,但也许更好的方法呢?

2 个答案:

答案 0 :(得分:1)

怎么样:

$cities = array('London', 'New York', 'Los Angeles');

$arr = array();
foreach($cities as $city) {
  $arr[] = $pack->findByCity($city); 
}

您可以将新城市添加到cities数组中,并将它们全部添加到$ arr变量

答案 1 :(得分:0)

您可以使用array_merge

$arr = array_merge($pack1->toArray(), $pack2->toArray(), $pack3->toArray());

在包对象中创建一个toArray方法。