PHP : Count number of JSON items/objects
Recently I need to paginate the search result returned by ElasticSearch. To paginate the result with standard CodeIgniter paginate helper.... one of the requirements is to know in advance the total_rows
or the total number of rows to display.
Since ElasticSearch is not really a SQL database and my knowledge of ElasticSearch is at minimum just to get it running. I decided to use PHP's count
function to get the total_rows
... by counting the items/objects inside JSON array.
To achieve this, first we need to encapsulate the result returned from ElasticSearch into JSON format with json_encode
$json_data = json_encode($this->elasticsearch->advancedquery("type", $searchquery));
next, decode it back
$decoded = json_decode($json_data);
and get the total_rows
for configuring the pagination with
$config['total_rows'] = count($decoded->hits->hits);
NOTE : To find the number of returned result or hits
or other result variables that you want to capture....you can do this to see all the result output.
echo "<pre>";
print_r($json_data);
echo "</pre>";
Hope this tutorial can help you to count the number of items or objects inside JSON array.
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+32.6k Golang : How to check if a date is within certain range?
+6.6k Golang : How to solve "too many .rsrc sections" error?
+5.8k Linux/MacOSX : Search for files by filename and extension with find command
+13.6k Golang : Human readable time elapsed format such as 5 days ago
+18.1k Golang : Read binary file into memory
+4.9k Golang : Customize scanner.Scanner to treat dash as part of identifier
+16.3k Golang : Delete files by extension
+17.8k Golang : Convert IPv4 address to decimal number(base 10) or integer
+6.5k Golang : Experimental emojis or emoticons icons programming language
+6.8k Javascript : How to get JSON data from another website with JQuery or Ajax ?
+6.2k PHP : Proper way to get UTF-8 character or string length
+11k Golang : How to pipe input data to executing child process?