让我先解释一下我的问题。我有一个简单的值对象Poi
。为了简单起见,本示例中省略了私有属性和 getter/setter。
class Poi implements JsonSerializable
{
public $latitude;
public $longitude;
public $category;
public function __construct($category, $lat, $long)
{
$this->category = $category;
$this->latitude = $lat;
$this->longitude = $long;
}
public function jsonSerialize()
{
return array(
'lat' => $this->latitude,
'lng' => $this->longitude,
);
}
}
一些数据提供者负责返回一组 Poi。IE
class PoiProvider1
{
public function getPois()
{
return array(
new Poi('airport', 10, 10),
new Poi('airport', 10, 15),
new Poi('restaurant', 30, 30),
)
}
}
class PoiProvider2
{
public function getPois()
{
return array(
new Poi('hotel', 20, 20),
new Poi('airport', 30, 30),
)
}
}
现在我想要一个结构如下的数组,我可以json_encode()
array(
'airport' => array(
new Poi('airport', 10, 10),
new Poi('airport', 10, 15),
new Poi('airport', 30, 30),
),
'restaurant' => array(
new Poi('restaurant', 30, 30),
),
'hotel' => array(
new Poi('hotel', 20, 20),
)
);
在 json_encode 之后,最终会形成以下结构:
{
"airport":[
{"lat":10,"lng":10},
{"lat":10,"lng":15},
{"lat":30,"lng":30}
],
"restaurant":[
{"lat":30,"lng":30}
],
"hotel":[
{"lat":20,"lng":20}
]
}
我可以使用array_merge
和一些数组复制来创建这样的结构,如下所示:
$provider1 = new PoiProvider1();
$provider2 = new PoiProvider2();
$pois = array_merge($provider1->getPois(), $provider2->getPois());
$poisNew = array();
foreach ($pois as $poi)
{
$poisNew[$poi->category][] = $poi;
}
显然,在处理大量 poi 时,这会消耗内存并且速度很慢。必须有一些更好更快的方法(即使用迭代器),但我不知道如何解决这个问题。谁能给我一些指示如何进行?