Combining Multidimensional Array Values in PHP

前端 未结 3 1636
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-22 08:19

I have a multidimensional array which looks like this:

Array
(
    [0] => Array
        (
            [0] => Array
                (
                           


        
相关标签:
3条回答
  • 2020-12-22 08:47

    I'm not going to write code because I agree with deceze.

    Nonetheless, my recommendation would be a custom function that:

    • loops over an input array
    • applies the logic you outlined
    • return the condensed array

    Given your specific requirements isn't a single, magical PHP function that does this. Yet, there are dozens of PHP array functions you could utilize within your custom function.

    If you need help on a particular piece, update your post or ask a new question.

    0 讨论(0)
  • 2020-12-22 08:48

    I would recommend using the array_walk function with a callback that handles your specific requirements for addition and uniqueness.

    0 讨论(0)
  • 2020-12-22 09:05

    I think this would work:

    $final=array(); // the final array
    $count=array(); // keeps track of instances of each description
    $loops=count($array);
    for($a=0;$a<$loops;$a++){
        foreach($array[$a] as $s){ //loop through child arrays
            if($count[$s['description']]>0){ //check if description exists in $count
                foreach($final as $k=>$v){ //add sums to the final if it does exist
                    if($final[$k]['description']==$s['description']){$final[$k]['shipping-amount']+=$s['shipping-amount'];}
                }
            }else{ //if it doesn't exist in the count array, add it to the final array
                $final[]=$s;
            }
            $count[$s['description']]++;//update the count array
        }
    }
    //Unset singletons, using the count array
    foreach($count as $k=>$v){
        if($v==1){
            foreach($final as $key=>$val){
                if($final[$key]['description']==$k){unset($final[$key]);}
            }
        }
    }
    print_r($final);
    

    I have been stuck on an issue for the past 2 days and feel you, so I hope this helps.

    0 讨论(0)
提交回复
热议问题