Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PHP Laravel filtering array from API

I’m using the Laravel Http client and getting the data from external API.
When I create schedules and post to the API, I’m getting the result like this:

[
  {
    "id": "321322",
    "date": "2024-03-21",
    "serviceTimeRange": {
      "startHour": "10:00",
      "endHour": "12:00",
      "id": "212367",
      "service": {
        "id": "333444",
        "serviceCode": "press"
      }
    }
  },
  {
    "id": "565332",
    "date": "2024-03-21",
    "serviceTimeRange": {
      "startHour": "12:00",
      "endHour": "14:00",
      "id": "234892",
      "service": {
        "id": "333444",
        "serviceCode": "press"
      }
    }
  },
  {
    "id": "785434",
    "date": "2024-03-22",
    "serviceTimeRange": {
      "startHour": "10:00",
      "endHour": "12:00",
      "id": "993218",
      "service": {
        "id": "777888",
        "serviceCode": "conference"
      }
    }
  }
]

As you can see from the result, in the first and the second record, the service->id has a same id (333444).

If I loop like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

@foreach($schedules as $schedule)
  <tr> 
    <td> {{ date('d-M-Y', strtotime($schedule->date)) }} </td>
    <td> {{ $schedule->serviceTimeRange->service->serviceCode }} </td>
  </tr>
@endforeach

I’m getting the result:

21-Mar-2024
press

21-Mar-2024
press

22-Mar-2024
conference

The question is: How can I combine the result that has same date and to be like this:

21-Mar-2024 
press
2 //where 2 is the count of the serviceTimeRange hours


22-Mar-2024
conference
1 //where 1 is the count of the serviceTimeRange hours

>Solution :

You can achieve this by grouping the schedules by date and then counting the number of serviceTimeRange for each date. First, convert the array of schedules to a Laravel collection.

$schedules = collect($schedules);

Then, group the schedules by date.

$grouped = $schedules->groupBy('date');

Now, you can loop through the grouped schedules in your view and count the number of serviceTimeRange for each date.

@foreach($grouped as $date => $schedules)
  <tr> 
    <td> {{ date('d-M-Y', strtotime($date)) }} </td>
    <td> {{ $schedules->first()->serviceTimeRange->service->serviceCode }} </td>
    <td> {{ $schedules->count() }} </td>
  </tr>
@endforeach
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading