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
+9.8k Golang : Ordinal and Ordinalize a given number to the English ordinal numeral
+9.6k Golang : Find correlation coefficient example
+9.1k Golang : How to find out similarity between two strings with Jaro-Winkler Distance?
+17.4k Golang : Clone with pointer and modify value
+12.2k Golang : Validate email address
+6.2k Unix/Linux : Use netstat to find out IP addresses served by your website server
+8.1k Golang : Reverse text lines or flip line order example
+5.3k Golang : fmt.Println prints out empty data from struct
+4.5k Linux : sudo yum updates not working
+9.3k Golang : Find the length of big.Int variable example
+5.7k Cash Flow : 50 days to pay your credit card debt
+15.4k Golang : ROT47 (Caesar cipher by 47 characters) example