1

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']]]];
    }

2 Answers 2

2

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Nailed it, thanks!
2

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

1 Comment

Thank you for this, I just tried this as well and it works perfectly too!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.