JSON loop with PHP

2

I have the following jSON

{
"nome": "Alisson",
"nome": "Bruno",
"nome": "Junior",
"nome": "Nicolly",
"nome": "José",
"nome": "Greice",
"idade": "20",
"idade" : "21",
"idade" : "29",
"idade" : "14",
"idade" : "11",
"idade" : "20"
}

I want to loop everyone. What is the best solution with the PHP language.

    
asked by anonymous 27.07.2014 / 21:30

2 answers

5
  • Step 1: Transform JSON into Array using json_decode() ;
  • Step 2: Use foreach in Array previously generated.
  • 27.07.2014 / 21:48
    1

    What you want is to loop in the object fields you can do by following the following implementation.

    $objeto = json_decode('{
    "nome": "Alisson",
    "idade":"19",
    "profissao":"programador"
    }', true);
    
    
    
    foreach($objeto as $item){
       print $item. "\n";
    }
    

    The json_decode() function of PHP Transforms a String JSON into an Object Array of PHP o First parameter receives the string the second receives a Boolean value that will inform you if your object will be of type Array or StDclass .

    Finally you access each field with a foreach , the variable item is the field corresponding to the loop

      

    You can see his example here .

        
    28.07.2014 / 16:24