2013-08-16 217 views
1

所以我想用PHP搜索JSON文件。 json鏈接:http://media1.clubpenguin.com/play/en/web_service/game_configs/paper_items.json。我只是把JSON文件放入我的網絡服務器。下面我的腳本:閱讀JSON文件?

<?php 
    $query = $_GET['s']; 

    $terms = explode(' ', $query); 
    $results = array(); 

    foreach(file('items.json') as $line) { 
     $found = true; 

     foreach($terms as $term) { 
      if(strpos($line, $term) == false) { 
       $found = false; 
       break; 
      } 
     } 

     if($found) { 
      $results[] = $line; 
     } else { 

     } 
    } 
    print_r($results); 

問題是它顯示了整個json文件而不是我的$查詢。我能做些什麼來解決這個問題?

+0

[json_decode(http://www.php.net/json_decode]可能是你在找什麼嘗試'json_decode(的file_get_contents( 「items.json」),TRUE);' – Orangepill

+0

不,只是一堆的錯誤 – Timmy6118CP

+0

什麼數據是你打算通過搜索? – Orangepill

回答

1

您可以使用json_encode,array_filter和閉包(PHP 5.3+)來完成此操作。

$obj = json_decode(file_get_contents("http://media1.clubpenguin.com/play/en/web_service/game_configs/paper_items.json"), true); 

$termStr = "ninja kiwi"; 
$terms = explode(" ", $termStr); 

$results = array_filter($obj, function ($x) use ($terms){ 
    foreach($terms as $term){ 
     if (stripos($x["label"], $term) || 
      stripos($x["paper_item_id"], $term)) 
     { 
      return true; 
     } 
    } 
    return false; 
}); 

echo json_encode($results); 
+0

謝謝OrangePill!有什麼辦法可以改變print_r來回顯?我做到了,但我得到和錯誤:數組字符串轉換在C:\ xampp \ htdocs \程序\測試\ index.php第18行 – Timmy6118CP

+0

@ Timmy6118CP你想打印JSON退出?如果是這樣,只需將'print_r($ results);'改爲'echo json_encode($ results);' – Orangepill

+0

@ Timmy6118CP,真的嗎?也許你應該聘請一個人。 – Rob