0

Как суммировать элементы массива таким образом

`Collection {#263 ▼
  #items: array:3 [▼
    0 => {#275 ▼
      +"platform": "Google"
      +"positive": "10"
      +"negative": "5"
      +"blocked": "1"
    }
    1 => {#274 ▼
      +"platform": "Yandex"
      +"positive": "6"
      +"negative": "2"
      +"blocked": "1"
    }
    2 => {#269 ▼
      +"platform": "Google"
      +"positive": "15"
      +"negative": "35"
      +"blocked": "23"
    }
  ]
}`

что бы получить

`Collection {#263 ▼
  #items: array:3 [▼
    0 => {#274 ▼
      +"platform": "Yandex"
      +"positive": "6"
      +"negative": "2"
      +"blocked": "1"
    }
    1 => {#269 ▼
      +"platform": "Google"
      +"positive": "25"
      +"negative": "40"
      +"blocked": "24"
    }
  ]
}`

1 ответ 1

2
$result = array_values(array_reduce($array, function($carry, $item) {
    foreach($item as $k => $v) {
        if (isset($carry[$item['platform']][$k])) {
            if (is_numeric($v)) $carry[$item['platform']][$k] += $v;
        }
        else $carry[$item['platform']][$k] = $v;
    }

    return $carry;
}, []));

print_r($result);

https://3v4l.org/ZJu8B

12
  • У меня почему то выдает array_reduce() expects parameter 1 to be array, object given
    – x1ds
    25 ноя 2019 в 9:41
  • @Денис, вероятно, вам нужно будет определить свой массив до использования функций. Откуда вы берете данные?
    – user285292
    25 ноя 2019 в 9:43
  • joxi.ru/823jPjKh9M03vm $reviews = \DB::table('reviews')->where('company_id', $id)->select('platform', 'positive', 'negative', 'blocked')->get();
    – x1ds
    25 ноя 2019 в 9:48
  • Покажите, как вы используете мою функцию?
    – user285292
    25 ноя 2019 в 9:50
  • 1
    Заработало!!! От души спасибо!
    – x1ds
    25 ноя 2019 в 11:23

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.