1

所以我想用 PHP 搜索一个 JSON 文件。json 链接: http: //media1.clubpenguin.com/play/en/web_service/game_configs/paper_items.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 文件而不是我的 $query。我能做些什么来解决这个问题?

4

1 回答 1

1

You can use json_encode, array_filter and a closure (PHP 5.3+) to accomplish this.

$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);
于 2013-08-16T22:17:56.197 回答