如何在更短的时间内在PHP中过滤更大的JSON对象?

时间:2014-11-28 14:18:06

标签: php json array-filter

所以我有一个JSON对象返回2500到5000个对象之间的任何地方,我能够过滤JSON对象,但它需要大约5到10秒,具体取决于我正在搜索的关键字。

以下是我的代码段

$jsonurl = "http://something.com/getitems.php";
$json = file_get_contents($jsonurl);
$json_output = json_decode($json);
$filteredArray = array_filter($json_output, function($obj) use ($keyword)
{ 
    return strpos(strtolower($obj->title), strtolower($keyword));
});
foreach($filteredArray as $obj){
    $date = "{$obj->pubDate}";
    $date = str_replace("GMT"," GMT" ,$date);
    $pBB[] = array(
        'source' => "{$obj->source}",
        'title' => "{$obj->title}",                
        'link' => "{$obj->link}",
        'imgLink' => "{$obj->imgLink}",
        'pubDate' => $date,
    );
}
echo json_encode($pBB);

除了缓存结果之外,还有其他任何方法可以提高性能并更快地返回结果吗?

提前致谢

1 个答案:

答案 0 :(得分:2)

一个简单的优化:考虑到$keyword并未改变,您不必每次都致电strtolower()。只是做:

$keyword = strtolower($keyword)
$filteredArray = array_filter($json_output, function($obj) use ($keyword)
{ 
    return strpos(strtolower($obj->title), $keyword);
});

更好的是,您可以使用内置函数进行不区分大小写的搜索,而不是在两个字符串上应用strtolower

int stripos ( string $haystack , string $needle [, int $offset = 0 ] )