Home > Software design >  How to combine array with same values
How to combine array with same values

Time:11-19

Okay so not 100% sure how to even ask this correctly but I have an array that I'm trying to consolidate and group together based on each hour, and then data for each year underneath that time.

My current array looks like this:

[
  {
    "name": "7:00 AM",
    "data": [
      {
        "x": "2019",
        "y": 1
      }
    ]
  }, 
  {
    "name": "7:00 AM",
    "data": [
      {
        "x": "2020",
        "y": 221
      }
    ]
  }
]

So I'm looking to combine these into a single array based on the name value and then all of the data will be combined:

[
  {
    "name": "7:00 AM",
    "data": [
      {
        "x": "2019",
        "y": 1
      },
      {
        "x": "2020",
        "y": 221
      }
    ]
  }
]

EDIT: And just to add how I'm originally getting and formatting these values, I'm using Larvel and running the following query:

$shipments = Orders::whereNotNull('shipped_at')->groupBy(DB::raw('YEAR(created_at)'))->selectRaw('count(*) as count, HOUR(shipped_at) as hour')->selectRaw("DATE_FORMAT(created_at, '%Y') label")->orderBy('label')->orderBy('hour')->groupBy('hour')->get();

And that gives me the following data:

enter image description here

And then I'm building the original array like this:

$shipping_chart_year = [];
    foreach ($shipments as $item) {
        $hour = Carbon::parse($item['hour'] . ':00:00')->timezone('America/Chicago')->format('g:i A');
        $shipping_chart_year[] = ['name' => $hour, 'data' => [['x' => $item['label'], 'y' => $item['count']]]];
    }

CodePudding user response:

This functions formats array as you expected to have.

function formatArray($array){
    $response = [];
    $keysIndexes = [];
    foreach($array as $value) {
        if(!array_key_exists($value['name'], $keysIndexes)) {
            array_push($response, $value);
            $keysIndexes[$value['name']] = sizeof($keysIndexes);
        } else {
            array_push($response[$keysIndexes[$value['name']]]['data'], $value['data'][0]);
        }
    }
    return $response;
}

CodePudding user response:

if you want to achieve this with the Laravel Collections (you can do so much with it!), here you go (based on your current array structure).

It is much more readable and way easier to achieve.

$output = collect(json_decode($data, true))
    ->groupBy('name')
    ->transform(function ($items, $name) {
        // Merge nested arrays into one
        $data = $items->map(function ($item) {
            return $item['data'][0];
        })->toArray();

        return [
            'name' => $name,
            'data' => $data,
        ];
    })
    ->values() // removes the key 
    ->toJson(); // returns the collection to json
  • Related