Group json with PHP?

1

How do I group a json according to a field?

I have the following json:

{
  "origem": [
    {
      "id": 154826,
      "nm": "",
      "tp": "",
      "am": "",
      "sg": "SAO",
      "sq": 925
    },
    {
      "id": 2289,
      "nm": "",
      "tp": "",
      "am": "",
      "sg": "RIO",
      "sq": 925
    },
    {
      "id": 154826,
      "nm": "",
      "tp": "",
      "am": "",
      "sg": "SAO",
      "sq": 925
    }
  ]
}

I wanted to group it according to the id so it looks like this:

{
  "origem": [
    {
      "id": 154826,
      "nm": "",
      "tp": "",
      "am": "",
      "sg": "SAO",
      "sq": 925
    },
    {
      "id": 2289,
      "nm": "",
      "tp": "",
      "am": "",
      "sg": "RIO",
      "sq": 925
    }
  ]
}

In case it would be more remove the repeated items. Does anyone know how to do this?

    
asked by anonymous 25.04.2018 / 19:11

1 answer

1

First, you should take this information and transform it into a array , then make a loop of repetition to aggregate this information, which in the case I put id as a key, and then return that JSON example:

<?php    
$json = '{
  "origem": [
    {
      "id": 154826,
      "nm": "",
      "tp": "",
      "am": "",
      "sg": "SAO",
      "sq": 925
    },
    {
      "id": 2289,
      "nm": "",
      "tp": "",
      "am": "",
      "sg": "RIO",
      "sq": 925
    },
    {
      "id": 154826,
      "nm": "",
      "tp": "",
      "am": "",
      "sg": "SAO",
      "sq": 925
    }
  ]
}';    
$rs = (json_decode($json, true)); // transformando os dados em um array
$r0 = array(); // array novo
foreach($rs['origem'] as $r)
{
    $r0[$r["id"]] = $r; // agregando as chaves iguais       
}    
echo json_encode(array_values($r0), JSON_PRETTY_PRINT); // retornando ao json

IDEONE Example

    
25.04.2018 / 19:26