简体   繁体   中英

search through JSON with PHP

I'm a JSON and PHP noob, and need some help! I've got some json, and want to search by user with _GET, and return all the info about that user.

JSON:

{
Shawn Taylor: {
  user: "Shawn Taylor",
  email: "email@example.com",
  phone: "604-123-4567"
  },
John Smith: {
  user: "John Smith",
  email: "email2@example.com",
  phone: "604-123-4569"
  }

FORM:

<form method="get">
  <input name="find" />
  <button type="submit">Find</button>
</form>

PHP:

if (!empty($_GET['find'])){
  $find = ($_GET['find']);
  $data_url = 'data.json';
  $data_json = file_get_contents($data_url);
  $data_array = json_decode($data_json, true);
  echo $data_array['user'];
  echo $data_array['email'];
  echo $data_array['phone'];

I thought this should work, but no such luck. Can anyone help please?

You just forgot to locate it with the $find key.

Try that (look at the 4 last lines) :

if (!empty($_GET['find'])){
  $find = ($_GET['find']);
  $data_url = 'data.json';
  $data_json = file_get_contents($data_url);
  $data_array = json_decode($data_json, true);

  $user = $data_array[$find];
  echo $user['user'];
  echo $user['email'];
  echo $user['phone'];
}

You never use $find.

if (isset($data_array[$find])) {
    $user = $data_array[$find];
    echo $user['user'];
    echo $user['email';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM