2

Here's the json code :

"Results":[{"username":"test","password":"test"},{"username":"test","password":"test"},{"username":"google","password":"test"},{"username":"yahoo","password":"test"}]}

You can see that it contains multiple values. I want to search within this code.

I want to get password of username : google

Is there any way to do that using php?

Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
codecute
  • 39
  • 1
  • 2
  • 5

2 Answers2

3

The json code is a data representation. You can either treat it as a string, and use php's string parsing functions to get what you need, or you can load this into an array or an object. I will focus on the array approach, as it maintains the structure the JSON was intended to represent. There is a function json_decode() which will take your json and turn it into an array:

$jsondata = '{"Results":[{"username":"test","password":"test"},
             {"username":"test","password":"test"},
             {"username":"google","password":"test"},
             {"username":"yahoo","password":"test"}]}';
$jsonArray = json_decode($jsondata, true);

Once you have this array, you can loop through it to find the value you want:

foreach($jsonArray["Results"] as $user) {
    if($user['username'] == 'google') {
        echo "Password = " . $user['password'];
    }
}

That should pretty much handle your case. Note that your JSON is missing a "{" Before the "Results" element, you can go here to validate your JSON code before running json_decode on it.

gabe.
  • 499
  • 2
  • 11
2

From the php manual :

<?php
$json = '{"foo-bar": 12345}';
$obj = json_decode($json);
print $obj->{'foo-bar'}; // 12345
?>

Then you could make a loop on the object ($obj) with test case (if/else) or switch case

Tarek
  • 3,810
  • 3
  • 36
  • 62
  • using if/else can be slow as searching from 100s of results :) any substitute ? – codecute Aug 12 '11 at 15:17
  • +1. But note that you will be able to traverse only one level deep with that. To access deeper level you'll have to chain that: $obj->{'level1'}->{'level2'}->{'level3'} – J0HN Aug 12 '11 at 15:17
  • switch case if faster than if/else , more info here : http://stackoverflow.com/questions/97987/switch-vs-if-else – Tarek Aug 12 '11 at 15:24
  • and here the how to implement it http://php.net/manual/en/control-structures.switch.php – Tarek Aug 12 '11 at 15:25