degath degath - 2 months ago 7
JSON Question

How to echo special value from key in array/json structure

I can easly explore json for example:

foreach($json_a['somwhere'][1]['somwhere_deeper'] as $something){
var_dump($something);
}


This code makes me print something like this:

C:\wamp64\www\dothejob.php:7:
array (size=2)
'name' => string 'John' (length=17)
'value' => string '15' (length=4)
C:\wamp64\www\dothejob.php:7:
array (size=2)
'name' => string 'Joanna' (length=6)
'value' => string '23' (length=2)
C:\wamp64\www\dothejob.php:7:
array (size=2)
'name' => string 'John' (length=17)
'value' => string '55' (length=10)
C:\wamp64\www\dothejob.php:7:
array (size=2)
'name' => string 'Joanna' (length=11)
'value' => string '55' (length=5)


So I'm sure I'm in a right place, but now the question is how to print only value which is in array, where name is Joanna?

I know it should be easy If statement, but I'm not sure how those keys/values works, Its easy question, but I'm beginner with php... :) ps. I was looking for help but didn't found solution yet.

Can't use $something[n], because they are not allways on the same "place", so only right solution is something like this:

I'm looking for something like this:

if 'name' is 'Joanna':
print value of 'value'

Answer

You can use $something[n] because you have an associative array :

foreach($json_a['somwhere'][1]['somwhere_deeper'] as $something){
    if ($something['name'] == 'Joanna') {
        var_dump($something);
    }
}

Output should be :

C:\wamp64\www\dothejob.php:7:
array (size=2)
  'name' => string 'Joanna' (length=6)
  'value' => string '23' (length=2)
C:\wamp64\www\dothejob.php:7:
array (size=2)
  'name' => string 'Joanna' (length=11)
  'value' => string '55' (length=5)

Of course, if you want to var_dump the value only, use var_dump($something['value']).

Comments