php remove duplicates from multidimensional array by value

前端 未结 4 941
臣服心动
臣服心动 2020-12-20 13:52

I would like to remove duplicates by value as you can see from the list_title. I know there are several questions and answers to this but their solution doesn\'

4条回答
  •  粉色の甜心
    2020-12-20 14:31

    Just loop through the arrays and keep track of duplicate field entries.

    Only the list_id and list_title will be considered for duplicate arrays but extra fields can be added. All the other keys are ignored.

     86,
            "list_reference" => 130948,
            "list_title" => "Offer:  apartment 2+kk",
            "list_city" => "Prague",
            "list_date" => "2017-03-03 11:20:35",
            "list_status" => 0,
            "list_creator" => "Company A",
            "list_price" => 30000,
            "list_furniture" => '""1","0","0""',
            "list_accommodation" => "flat"
        ],
        [
            "list_id" => 87,
            "list_reference" => 130947,
            "list_title" => "Offer:  apartment 2+kk", 
            "list_date" => "2017-03-03 11:20:35",
            "list_status" => 0,
            "list_creator" => "Company B",
            "list_price" => 30000,
            "list_furniture" => '""1","0","0""',
            "list_accommodation" => "flat"
        ]
    ];
    
    
    $duplicateFields = ["list_id" => array(), "list_title" => array()];
    foreach ($array as $index => $value) {
        if(in_array($value['list_id'], $duplicateFields['list_id']) || in_array($value['list_title'], $duplicateFields['list_title'])){
            unset($array[$index]);
        }else{
            array_push($duplicateFields['list_id'], $value['list_id']);
            array_push($duplicateFields['list_title'], $value['list_title']);
        }
    }
    
    var_dump($array);
    

    Which yields:

    array(1) {
      [0]=>
      array(10) {
        ["list_id"]=>
        int(86)
        ["list_reference"]=>
        int(130948)
        ["list_title"]=>
        string(22) "Offer:  apartment 2+kk"
        ["list_city"]=>
        string(6) "Prague"
        ["list_date"]=>
        string(19) "2017-03-03 11:20:35"
        ["list_status"]=>
        int(0)
        ["list_creator"]=>
        string(9) "Company A"
        ["list_price"]=>
        int(30000)
        ["list_furniture"]=>
        string(13) """1","0","0"""
        ["list_accommodation"]=>
        string(4) "flat"
      }
    }
    

提交回复
热议问题