Loop through array in PHP, decode JSON found in files of the same name as the values and assign the decoded JSON to properties

StackOverflow https://stackoverflow.com/questions/22119670

Question

I'm sorry about the complicated title - it's hard to explain my situation.

This is json/Egg.json:

{"1":{"name":"Egg"}}

This is index.php:

error_reporting(E_ALL);
class Test {

    public $arrEgg;
    public $arrTypes = array("Egg");

    public function __construct() {
        foreach($this->arrTypes as $strType) {
            if(file_exists("json/$strType.json"))
                $this->{'arr' . $strType} = json_decode(file_get_contents("json/$strType.json"), true);
            else
                echo "File json/$strType.json not found!";
         }
     }
 }

$test = new Test();
echo $test->arrEgg[1]['name']; // I've also tried $test->arrEgg['1']['name']

When I run index.php, there is no output. This is what I want it to output:

Egg
Was it helpful?

Solution

Try this:

<?php

class Test {

    public $arrEgg;
    public $arrTypes = array("Egg");

    public function __construct() {
        foreach($this->arrTypes as $strType) {
            if(file_exists("json/$strType.json"))
                $this->{'arr' .$strType} = json_decode(file_get_contents("json/$strType.json"), true);
            else
                echo "File json/$strType.json not found!";
         }
     }
 }

$test = new Test();
echo $test->arrEgg[0][1]['name'];

Output: Egg

Since you want to put data in the $arrEgg property, you'll want to append the $strType, such as $this->{'arr' .$strType}. NOT with $this->arr{$strType}.

Your JSON is nested, so you'll still need to access it via [0][1]['name'], unless you change your JSON to be: {"1":{"name":"Test"}}.

OTHER TIPS

You would parse it like that:

PHP

$json = '[{"1":{"name":"Egg"}}]';
$data =  json_decode($json);
echo $data[0]->{"1"}->{"name"};

Output:

egg

DEMO

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top