donglu1881 2015-06-10 15:02
浏览 139
已采纳

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

I have an array containing several objects.

$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"}
            ]

I'm trying to iterate trough this array and when the id is allready present in the array, I want to add the value of mergethis with the first hit that has the same id, seperated with a comma, and then unset the object from the array.

So my expected outcome would become:

[
{"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"}
]

I'm trying to iterate trough $products and compare the values but I'm stuck at comparing the value to a subvalue of the array in stead of to the entire array

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]);
    }
}

This obviously doesn't work because it compares the item to the entire array in stead of to the sub value id of the array item.

How do I go about getting my expected outcome?

Do I need to create a new array filled with the keys and id values of each array item and iterate trough that? Or is there an easier method to compare object values inside an array to each other?

  • 写回答

3条回答 默认 最新

  • drrw8672 2015-06-10 15:10
    关注

    Hint: Use associative array with id as key and the whole product as value:

    $results = array();
    foreach ($products as $prod){
        if (array_key_exists($prod['id'], $results)){
            $results[$prod['id']]['mergethis'] .= ',' . $prod['mergethis'];
        } else {
            $results[$prod['id']] = $prod;
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示