0

I am new to PHP and I have a pretty basic question for which I wasn't able to find an answer to. This is an example JSONObject:

{
    "biome":"forest",
    "id":"51134535488",
    "animals":[
        {"species":"bear", "age":"8", "gender":"male", "family":"mamal"},
        {"species":"hawk", "age":"3", "gender":"female", "family":"bird"},
        {"species":"elk", "age":"5", "gender":"male", "family":"mamal"},
        {"species":"spider", "age":"0.3", "gender":"female", "family":"insect"}
    ]
}

In it, we have a JSONArray, which holds four JSONObjects. How would I go about getting only the JSONArray from the JSONObject and then foreach looping it to get all the inner rows? I am working in Lumen framework, so a specific Lumen answer would be much apreciated (if it can be done differently in Lumen)!

Daelendil
  • 47
  • 1
  • 13
  • 3
    Possible duplicate of [How can I parse a JSON file with PHP?](https://stackoverflow.com/questions/4343596/how-can-i-parse-a-json-file-with-php) – Nick Feb 27 '19 at 20:46

3 Answers3

3

If for instance you want to display the four species:

$json = '{
    "biome":"forest",
    "id":"51134535488",
    "animals":[
        {"species":"bear", "age":"8", "gender":"male", "family":"mamal"},
        {"species":"hawk", "age":"3", "gender":"female", "family":"bird"},
        {"species":"elk", "age":"5", "gender":"male", "family":"mamal"},
        {"species":"spider", "age":"0.3", "gender":"female", "family":"insect"}
    ]
}';

foreach(json_decode($json)->animals as $animal) {
    echo $animal->species . "\n";
}
trincot
  • 317,000
  • 35
  • 244
  • 286
3

Here some useful lines you may use :

/* Set the json file directory */
$path = 'your path here';
/* here your json file name */
$jsonfile = 'youjsonfilename';
/* json decode */
$language = json_decode(file_get_contents($path . $jsonfile. '.json'));

Then if your json file look like this :

{
    "test": {
        "test1"                 : "test2",
     }
}

You must write in php this line to print "test2" for example :

<?php echo $language->test->test1; ?>
MimoudiX
  • 612
  • 3
  • 16
1

if you're starting out from a JSON string, meaning your example is a string variable in PHP you can you do something like this:

$jsonString = '{"biome" : "forest", ...}';
$forest = json_decode($jsonString, true); // Passing true as a second argument converts the JSON string into an array, instead of a PHP object

$animals = $forest['animals']; // If you're sure animals is always an array, you can do the following for loop without any problems
foreach ($animals as $animal) {
    var_dump($animal);
}
jlos
  • 1,010
  • 1
  • 8
  • 12