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 VS2022创建MVC framework提示:预安装的程序包具有对缺少的注册表值的引用
  • ¥15 weditor无法连接模拟器Local server not started, start with?
  • ¥20 6-3 String类定义
  • ¥15 嵌入式--定时器使用
  • ¥20 51单片机学习中的问题
  • ¥30 Windows Server 2016利用兩張網卡處理兩個不同網絡
  • ¥15 Python中knn问题
  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题