Group json with PHP?

Asked

Viewed 176 times

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?

  • But what about the "sg": "SAO", and "sg": "RIO",? Will get lost?

  • @Guilhermenascimento Not because all who repeat id are equal. So I only need one and eliminate the rest

  • I was just wondering, because I was thinking of suggesting something different but that I would group anyway.

1 answer

1


First, you must take this information and turn it into a array, then make a repeat loop to assault this information, in which case I put the id as key, and then return that JSON you want, 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.