简体   繁体   中英

Php array merge 2d array with same values

The output I am getting mentions the same date multiple times and I need to merge this.

Output I have:

[{"checkFullAuth":true},{"2019-11-14":0,"avail_slots":0,"dates":"2019-11-14"},{"2019-11-15":1,"avail_slots":6,"dates":"2019-11-15"},{"checkFullAuth":true},{"2019-11-14":1,"avail_slots":14,"dates":"2019-11-14"},{"2019-11-15":1,"avail_slots":7,"dates":"2019-11-15"},{"checkFullAuth":true},{"2019-11-14":1,"avail_slots":17,"dates":"2019-11-14"},{"2019-11-15":1,"avail_slots":11,"dates":"2019-11-15"}]

Output I need:

[{"checkFullAuth":true},{"2019-11-14":1,"avail_slots":0,"dates":"2019-11-14"},{"2019-11-15":1,"avail_slots":6,"dates":"2019-11-15"}]

PS: The value of a date can change 0/1, the 1 will be leading here. So if there is a date mentioned twice with both values 1 and 0, the merged result should be 1.

How can I get the output I need?

This is the function I tried to get the output I need but it doesn't work as expected, it returns the values multiple times:

public function filterDates($dates_array){
    $dates_merged_array = array();
    $n=0;
    foreach($dates_array as $date_row1){
        $n++;
        $date1 = $date_row1['dates'];
        foreach($dates_array as $date_row2){
            if($date_row2['dates'] == $date1){
                if($date_row1[$date1] == 1 || $date_row2[$date1] == 1){
                    $dates_merged_array[] = array($date1=>1,"avail_slots"=>max($date_row1['avail_slots'],$date_row2['avail_slots']),"dates"=>$date1);
                }
                else if($date_row1[$date1] == "skip" || $date_row2[$date1] == "skip"){
                    $dates_merged_array[] = array($date1=>"skip","avail_slots"=>max($date_row1['avail_slots'],$date_row2['avail_slots']),"dates"=>$date1);
                }
                else{
                    $dates_merged_array[] = array($date1=>0,"avail_slots"=>max($date_row1['avail_slots'],$date_row2['avail_slots']),"dates"=>$date1);
                }
            }
        }
    }
    return $dates_merged_array;
}

Define a unique key in each array and match that key for the reference and then check on based of that key check to generate the array or not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM