How to filter a larger JSON object in PHP in less time?

402 views Asked by At

So i have a JSON object which returns anywhere between 2500 to 5000 objects, I am able to filter the JSON object but its taking around 5 to 10 secs depending on the Keyword i am searching for.

Below is the my code snippet

$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);

Beside caching the results is their any other way to increase the performance and return the results faster?

Thanks in advance

1

There are 1 answers

0
dynamic On

One simple optimization: considering $keyword doesn't not change you don't have to call strtolower() each time. Just do:

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

Even better you could use the built-in function to do case-insensitive search, instead of applying strtolower on both strings

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