使用json的数组过滤器

时间:2017-01-27 09:08:29

标签: php

我无法尝试显示关联数组中存在某些数字(产品编号)。当我尝试这段代码时,我总是得到“假”。

[0] => stdClass Object
    (
        [areaid] => 1
        [area] => Fan
        [business] => ["51","53"]
        [city] => 4
    )

[1] => stdClass Object
    (
        [areaid] => 2
        [area] => Manchester
        [business] => ["51","53"]
        [city] => 4
    )

[2] => stdClass Object
    (
        [areaid] => 3
        [area] => Battery Park
        [business] => ["53"]
        [city] => 4
    )

[3] => stdClass Object
    (
        [areaid] => 3
        [area] => Battery Park
        [business] => ["52"]
        [city] => 4
    )

[4] => stdClass Object
    (
        [areaid] => 3
        [area] => Battery Park
        [business] => ["51","53"]
        [city] => 4
    )

我想显示这样的结果

[0] => stdClass Object
    (
        [areaid] => 1
        [area] => Fan
        [business] => ["51","53"]
        [city] => 4
    )

[1] => stdClass Object
    (
        [areaid] => 2
        [area] => Manchester
        [business] => ["51","53"]
        [city] => 4
    )

[2] => stdClass Object
    (
        [areaid] => 3
        [area] => Battery Park
        [business] => ["53","52","51"]
        [city] => 4
    )

有人帮我展示这个结果。

2 个答案:

答案 0 :(得分:0)

如果我找到了你,那么你是在尝试根据该地区对业务进行分组?

试试这段代码:

$groupedBusinesses = array();

foreach ($areas as $area) {
    if (array_key_exists($area->areaid, $groupedBusinesses)) {        
        $groupedBusinesses[$area->areaid]->business = 
            array_merge($groupedBusinesses[$area->areaid]->business, $area->business);
    } else {
        $groupedBusinesses[$area->areaid] = $area
    }    
}

这将检查该区域是否已在列表中。如果不是,则会添加。如果是,则只将业务添加到列表中。

答案 1 :(得分:0)

如果你需要在结果数组中使用新对象,这可能会有所帮助:

$result = array();
$area   = array();
$i      = 0;
foreach ($array as $key => $obj) {
    if (!in_array($obj->area, $area)) {
        $result[$i]         = new Product($obj->areaid, $obj->area, $obj->business, $obj->city);
        $area[$obj->area]   = $i;
        $i++; 
    } else {
        $result[$area[$obj->area]]->addBusiness($obj->business);
    }
}



class Product {

    public $areaid;
    public $area;
    public $business;
    public $city;

    __construct($areaid, $area, $business, $city) {
        $this->areaid       = $areaid;
        $this->area         = $area;
        $this->business     = $business;
        $this->city         = $city;
    }

    public function addBusiness($int) {
        $this->business[] = $int;
    }
}



它将检查结果是否已包含此区域的条目。 如果是这样,它会将业务值添加到数组中。 如果不是ut将在结果数组的新位置创建一个新对象。