2013-08-16 2 views
1

그래서 PHP로 JSON 파일을 검색하려고합니다. json 링크 : http://media1.clubpenguin.com/play/en/web_service/game_configs/paper_items.json. 난 그냥 내 웹 서버에 JSON 파일을 넣어. Heres 내 스크립트 :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은] 당신이 찾고있는 것을 아마도) ("items.json를"'json_decode (file_get_contents을 시도, 사실). ' – 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을 변경할 수있는 방법이 있습니까? 나는 그것을했다 그러나 나는 얻는다 : 배열 18에 C : \ xampp \ htdocs \ Programs \ Test \ index.php에 문자열 변환 – Timmy6118CP

+0

@ Timmy6118CP 당신은 json를 밖으로 인쇄하는 것을 시도하고있다? 그렇다면'print_r ($ results);을'echo json_encode ($ results);로 변경하십시오. – Orangepill

+0

@ Timmy6118CP, 정말요? 어쩌면 당신은 누군가를 고용해야합니다. – Rob

관련 문제