如何比较数组内的对象值?

时间:2015-06-10 15:02:15

标签: php arrays object

我有一个包含多个对象的数组。

$products = [
            {"id":"1","random":"sadasd","mergethis":"Ding"},
            {"id":"2","random":"assdfsadf","mergethis":"Ding"},
            {"id":"2","random":"assdfsadf","mergethis":"Flop"},
            {"id":"2","random":"assdfsadf","mergethis":"Bips"},
            {"id":"3","random":"sdfss","mergethis":"Flung"},
            {"id":"3","random":"sdfss","mergethis":"Rorg"},
            {"id":"4","random":"asdasdddaf","mergethis":"Shwung"}
            ]

我正在尝试通过这个数组进行迭代,当id已经存在于数组中时,我希望将mergethis的值添加到具有相同{{1}的第一个匹配项中用逗号分隔,然后从数组中取消设置对象。

所以我的预期结果会变成:

id

我正在试图通过[ {"id":"1","random":"sadasd","mergethis":"Ding"}, {"id":"2","random":"assdfsadf","mergethis":"Ding,Flop,Bips"}, {"id":"3","random":"sdfss","mergethis":"Flung,Rorg"}, {"id":"4","random":"asdasdddaf","mergethis":"Shwung"} ] 进行迭代并比较这些值,但我坚持将值与数组的子值进行比较而不是整个数组

$products

这显然不起作用,因为它将项目与整个数组进行比较,而不是数组项的子值foreach($products as $key => $value){ if (in_array($value->id, $products)) { //Delete this item and add product_category comma sepereated to first item //unset($products[$key]); } }

如何获得预期的结果?

我是否需要创建一个新数组,其中包含每个数组项的键和id值,并通过它进行迭代?或者是否有更简单的方法来比较数组内的对象值?

3 个答案:

答案 0 :(得分:2)

提示:使用以id为关键字的关联数组,将整个产品用作值:

$results = array();
foreach ($products as $prod){
    if (array_key_exists($prod['id'], $results)){
        $results[$prod['id']]['mergethis'] .= ',' . $prod['mergethis'];
    } else {
        $results[$prod['id']] = $prod;
    }
}

答案 1 :(得分:1)

$result = [];
foreach ($products as $value) {
    if (!isset($result[$value['id']])) {
        $value['mergethis'] = [$value['mergethis']];
        $result[$value['id']] = $value;
    } else {
        $result[$value['id']]['mergethis'][] = $value['mergethis'];
    }
}

这似乎是最明智的。如果确实需要将逗号连接的数组放入一个字符串中:

foreach ($result as &$value) {
    $value['mergethis'] = join(',', $value['mergethis'];
}

答案 2 :(得分:0)

您基本上正在寻找pluck的PHP实现。看看this gist for a PHP version

$ids_array = array_pluck("id", $products); // get just he id values
$ids_array = array_unique($ids_array); // remove duplicates
foreach($products as $key => $value){
    if (in_array($value->id, $ids_array)) {
        //Delete this item and add product_category comma sepereated to first item
        //unset($products[$key]);
    }
}
function array_pluck ($toPluck, $arr) {
    return array_map(function ($item) use ($toPluck) {
        return $item[$toPluck];
    }, $arr); 
}