How to delete repeated names with loaded values?

Asked

Viewed 53 times

2

I have the following names from JSON in this sequence

[
   {
      "Animal":"Leão"
   },
   {
      "Animal":"Leopardo"
   },
   {
      "Especie":"Aves"
   },
   {
      "Especie":"Mamiferos"
   },
   {
      "Especie":"Répteis"
   },
   {
      "Animal":"Cachorro"
   },
   {
      "Animal":"Gato"
   },
   {
      "Especie":"Peixes"
   }
]

Notice that the names that are behind the ':' repeat themselves and are randomly disorganized, I wanted to stay in this model:

Animal:

Lion

Leopard

Dog

Pussycat

Species:

Birds

Nipples

Reptiles

Pisces

I need the exit to be via: echo organised, as in the second case.

How can I do this? Do I need to use Dictionaries and increase the values in the keys?

  • Hello Sergio, welcome to Sopt! Enter the JSON that is received. The sequence you placed is not a JSON. This will help someone answer your question more precisely.

  • 1

    Oh yes, I’m better now

1 answer

2


It depends a little on how you receive this json by php. Admitting this json:

[
 {"Animal":  "Leão"},{"Animal":  "Leopardo"},
 {"Especie": "Aves"},{"Especie": "Mamiferos"},
 {"Especie": "Répteis"},{"Animal":  "Cachorro"},
 {"Animal":  "Gato"},{"Especie": "Peixes"}
]

One way to do it may be the following:

$array = json_decode($contents,true);
//cria duas variaveis para guardar classificações repetidas
$animals = array();
$species = array();

//varre o array gerado pelo json 
foreach ($array as $key => $value) {
    //colocando valores em suas respectivas categorias
    if (array_key_exists("Animal", $value)){ 
         array_push($animals ,$value["Animal"]); 
    }elseif(array_key_exists("Especie", $value)){
         array_push($species ,$value["Especie"]);
     } 
}

//resultado será um array com chaves das categorias repetidas
//que levam as os valores
$result = array("Animal" => $animals, "Especie" => $species);

//imprimindo
foreach ($result as $key => $value) {
    echo "{$key}:  \n";
    foreach($value as &$v){
        echo "\t {$v} \n";
    }
 }

come out like this:

Animal:
     Leão
     Leopardo
     Cachorro
     Gato
Especie:
     Aves
     Mamiferos
     Répteis
     Peixes

Browser other questions tagged

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