Объединение значений многомерных массивов в PHP

У меня многомерный массив, который выглядит так:

Array ( [0] => Array ( [0] => Array ( [description] => UPS Ground [delivery-time] => 1-5 business days [shipping-amount] => 1299 ) [1] => Array ( [description] => UPS 3 Day Select [delivery-time] => 3 business days [shipping-amount] => 2459 ) [2] => Array ( [description] => UPS 2nd Day Air [delivery-time] => 2 business days [shipping-amount] => 3239 ) ) [1] => Array ( [0] => Array ( [description] => UPS Ground [delivery-time] => 1-5 business days [shipping-amount] => 864 ) [1] => Array ( [description] => UPS 3 Day Select [delivery-time] => 3 business days [shipping-amount] => 1109 ) [2] => Array ( [description] => UPS 2nd Day Air [delivery-time] => 2 business days [shipping-amount] => 1633 ) [3] => Array ( [description] => UPS Overnight [delivery-time] => 1 business day [shipping-amount] => 3528 ) ) ) 

Я пытаюсь достичь 3 вещей:

  1. Добавьте значения shipping-amount где description одинаково для всех измерений
  2. Удалите array если он содержит description которое не существует в каждом другом измерении
  3. Снимите измерение, когда суммы доставки объединены

Может быть несколько массивов первого уровня (не только 2, как показано здесь), но это так же глубоко, как и размеры. Я ищу следующий результат:

 Array ( [0] => Array ( [description] => UPS Ground [delivery-time] => 1-5 business days [shipping-amount] => 2163 ) [1] => Array ( [description] => UPS 3 Day Select [delivery-time] => 3 business days [shipping-amount] => 3568 ) [2] => Array ( [description] => UPS 2nd Day Air [delivery-time] => 2 business days [shipping-amount] => 4872 ) ) 

Заранее спасибо!

Я думаю, что это сработает:

 $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); 

Я застрял в проблеме за последние 2 дня и чувствую вас, поэтому надеюсь, что это поможет.

Я не собираюсь писать код, потому что согласен с децезией .

Тем не менее, моя рекомендация была бы специальной функцией, которая:

  • петли над входным массивом
  • применяет описанную вами логику
  • вернуть сконденсированный массив

Учитывая ваши конкретные требования, это не одна, волшебная функция PHP, которая делает это. Тем не менее, существуют десятки функций массива PHP, которые вы могли бы использовать в своей пользовательской функции.

Если вам нужна помощь по определенной части, обновите сообщение или задайте новый вопрос.

Я бы рекомендовал использовать функцию array_walk с обратным вызовом, который обрабатывает ваши конкретные требования для добавления и уникальности.