degath
degath

Reputation: 1621

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'

Upvotes: 0

Views: 75

Answers (2)

Anuj
Anuj

Reputation: 41

you need to update naming convension of Variable

foreach($json_a['somwhere'][1]['somwhere_deeper'] as $key => $value){
    echo $key." : ".$value
}

Output of above code will be something like John : 15 Johnna : 23

foreach(array as key => value)
{
 //key represent array key
//value represent value of that array
}

Let me know in case of any concern.

Upvotes: 0

roberto06
roberto06

Reputation: 3864

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']).

Upvotes: 1

Related Questions