Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a faster way for searching item in json array

Tags:

json

php

Let says that I stored dataID in json file with 1,000,000 records.

My zresults.json = {"dataID":["1","2","3", ... "1000000"]}z

I want to find ID "100000" in the array.

$file = file_get_contents('results.json');
$data = json_decode($file,true);
if(in_array('100000', $data['dataID']))
{
  echo "found";
} else {
  echo "not found"; 
}

It took about 0.6 sec. for the result.

Is there a faster way for searching in json array like this?

Please give me an example!

Thank you in advance.

Update:

Although sql would much faster but considered 1,000,000 record in one table the more record the more space! At least, static file reduced server load and less space.

It depends on how designed your system. Use it the right place and the right time!

like image 449
webmastx Avatar asked Nov 28 '25 17:11

webmastx


2 Answers

Sure!

$stm = $pdo->prepare("SELECT 1 FROM data WHERE id = ?");
$stm->execute(array(100000));
if ($stm->fetchColumn())
{ echo "found"; } else { echo "not found"; }

you will need to import your array into database first.

like image 193
Your Common Sense Avatar answered Dec 01 '25 06:12

Your Common Sense


Depending on the structure of the data in the results.json file you may be able to do a simple string search for example

$file = file_get_contents('results.json');

if(strpos($file, '"100000"') !== false)
{
    echo 'found';
}
else
{
    echo 'not found';
}

After benchmarking your method I got around 0.78 seconds (on my slow local system) however with this method I achieved around 0.03 seconds.

Like I say, it depends on your data structure but if it does permit you to use this method you'll see significant speed benefits.

like image 25
olliefinn Avatar answered Dec 01 '25 06:12

olliefinn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!