Loop json with PHP

Asked

Viewed 408 times

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 make a loop with everyone. What is the best solution with the PHP language.

  • Want to loop in PHP? or Javascript? Already have the loop in the language you want or need to convert?

2 answers

5


  1. Step 1: Transform JSON into Array using json_decode();
  2. Step 2: Use foreach in the Arraypreviously generated.

1

What you want is to loop 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 function json_decode() PHP Transform a String JSON in an Object Array from PHP the First parameter receives the string the second receives a boolean value which you will inform if your object will be of the type Array Or StDclass.

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

You can see his example here.

Browser other questions tagged

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