reducing an array into another array

user12147861 :

Inside a laravel blade template, I am trying to reduce an array like this:

$longList = [['box' => 1, 'kg' => 2], ['box' => 2, 'kg' => 2], ['box' => 3, 'kg' => 3]];

into something like this: $reducedList = [['count' => 2, 'kg' => 2], ['count' => 1, 'kg' => 3]];

This is what I have so far:

@php
          $variableWeights = isset($sale->variable_weight_json) ? collect(json_decode($sale->variable_weight_json, true)) : null;
          $groups = array();

          if (isset($variableWeights)) {
            $groups = $variableWeights->reduce(function($carry, $item) {
              $index = array_search($item['kg'], array_column($carry, 'weight'));
              if (isset($index)) {
                $existing = $carry[$index];
                array_splice($carry, $index, 1, [
                  'count' => $existing['count'] + 1,
                  'weight' => $item['kg']
                ]);
              } else {
                array_push($carry, [
                  'count' => 1,
                  'weight' => $item['kg'],
                ]);
              }
              return $carry;
            }, array());
          }
        @endphp

But it is giving me the error Undefined offset: 0

I am new to php. How should the code be corrected or is there a better approach to achieve the desired result?

N69S :

Why dont you reduce it to something simpler like this

$reducedList = [2 => 2, 3 => 1]

where the weight is the index and the value is the count.

$reducedList = [];
foreach ($longList as $box) {
    if (isset($reducedList[$box['kg']]) {
        $reducedList[$box['kg']]++;
    } else {
        $reducedList[$box['kg']] = 1;
    }
}

This way you avoid complexity but you still get the same amount of information.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=26182&siteId=1