Skip to content
Advertisement

PHP read JSON Array with unknown variable

I have a Json Script with an Array inside and Array which looks like this shortened:

Array
(

    [assets] => Array
        (

            [CGGD.AS] => Array
                (
                    [shortName] => iShares Global Govt Bond Climat
                    [sector] => 
                    [industry] => 
                    [country] => 
                    [longBusinessSummary] => 
                    [currency] => USD
                    [marketCap] => 
                    [logo_url] => 
                    [Anlageklasse] => Anleihen
                    [Anmerkungen] => Staatsanleihen Welt
                    [Nachhaltigkeit] => 1
                    [Ist_Alternative] => 1
                    [weights] => 0.86563025602977
                )

            [SUOE.MI] => Array
                (
                    [shortName] => ISHARES EUR CORP BOND SRI UCITS
                    [sector] => 
                    [industry] => 
                    [country] => 
                    [longBusinessSummary] => 
                    [currency] => EUR
                    [marketCap] => 
                    [logo_url] => 
                    [Anlageklasse] => Anleihen
                    [Anmerkungen] => Unternehmensnaleihen EUR
                    [Nachhaltigkeit] => 1
                    [Ist_Alternative] => 1
                    [weights] => -0.47997445382071
                )

        )

    [risk] => 0.05323390949106
    [return] => 1.1125842376311
)

Now I want to work with the single variables shortName, industry, etc. When I tried to call the function with

print_r($json_data['assets']['CGGD.AS']['shortName']); 

it worked perfectly fine. When I use

print_r($_POST['assets'][0][0]); 

it is not working at all and gives me the following warning:

Warning: Undefined array key “assets” in C:xampphtdocstestergebnisdarstellung.php on line 52

Warning: Trying to access array offset on value of type null in C:xampphtdocstestergebnisdarstellung.php on line 52

The problem I have is that I will not know what name will be in the second brackets like CGGD.AS and because of this I can not use the working function. I will not now how long the array is either and numbers are not working. Because of this I do not know how to call the single variabless without using the name. How can I call the function?

Advertisement

Answer

To get all shortName you can loop your array:

foreach ($json_data['assets'] as $key => $data) {
    print_r($data['shortName']);
}

If you want just shortName of first element, then use current:

$item = current($json_data['assets']);

print_r($item['shortName']);
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement