How to group and create relationship from JSON response

Viewed 30

I am trying to group JSON data from API response and create a relationship from it. The data I am receiving is the statistics from live football games. The response includes arrays of live fixtures. Each fixture contains data about the leagues and teams. Different fixtures may be from the same league. Now I want to retrieve the leagues and group fixtures from the same league together while maintaining the league-fixture relationship. In a way, I can query league->fixtures() and get all fixtures under the league. Here is a sample response from the API enter image description here

Please help if you have a hint on how to achieve that. Thank in advance

1 Answers

It sounds like you want to group the items by league. Let's use our array_reduce friend for that. This is the basic syntax:

$arr = [
  [
    "leauge" => "sweeden",
    "fixture" => "12"
  ],
  [
    "leauge" => "sweeden",
    "fixture" => "13"
  ],
  [
    "leauge" => "germany",
    "fixture" => "14"
  ],
  [
    "leauge" => "france",
    "fixture" => "15"
  ],
];

$grouped = array_reduce($arr, function($agg, $item) {
  if (!isset($agg[$item['leauge']])) {
    $agg[$item['leauge']] = [];
  }
  $agg[$item['leauge']][] = $item;
  return $agg;
}, []);

print_r($grouped);

/*
// output:
Array
(
    [sweeden] => Array
        (
            [0] => Array
                (
                    [leauge] => sweeden
                    [fixture] => 12
                )

            [1] => Array
                (
                    [leauge] => sweeden
                    [fixture] => 13
                )

        )

    [germany] => Array
        (
            [0] => Array
                (
                    [leauge] => germany
                    [fixture] => 14
                )

        )

    [france] => Array
        (
            [0] => Array
                (
                    [leauge] => france
                    [fixture] => 15
                )

        )

)
*/
Related