I am looking for a way to count the number of items (in PHP) returned in these JSON strings I am getting when searching a database.
Forgive me because I'm utterly crap at all of this.
I was told because there is no count returned in the JSON version, like there is in the XML one from this database, I would have to use a loop to count the number of results?
I've had a look around but nothing seems to fit what I want to do...
The following is an example of the strings I get:
Array (
[0] => stdClass Object (
[score] => 12
[popularity] => 3
[name] => Samantha Dark
[id] => 151019
[biography] => [url] => http://www.themoviedb.org/person/151019
[profile] => Array ( )
[version] => 16
[last_modified_at] => 2011-04-11 17:17:33
)
[1] => stdClass Object (
[score] => 11
[popularity] => 3
[name] => Johnny Dark
[id] => 158737
[biography] => [url] => http://www.themoviedb.org/person/158737
[profile] => Array ( )
[version] => 14
[last_modified_at] => 2011-04-11 17:18:38
)
)
and if applicable, here's the php I use to reque开发者_StackOverflowst & decipher it
$name = $_GET['search'];
$persons_result = $tmdb->searchPerson($name);
$persons = json_decode($persons_result);
foreach ($persons as $person) {
echo '<a href="tmdb_person.php?id='.$person->id.'">'.$person->name.'</a></br>';
}
Use the count
function on $persons
to get the number of items.
This should do the trick.
$iCount = count($persons)
When you call json_decode
you're getting a PHP variable which contains an array of items and values.
Currently you're getting what's called a stdClass
but if you add true
parameter to your json_decode
function, you'll get a normal array. Although using the true
parameter or not, you can still call count
:)
$name = $_GET['search'];
$persons_result = $tmdb->searchPerson($name);
$persons = json_decode($persons_result, true);
print_r($persons);
There you go :)
If you run a query identical to below it will return the Item, and count unique items
$query = " SELECT table_column_here ,COUNT(*) FROM table_name GROUP BY table_column_here; ";
Which will return [{"column_name":"column_data_result","count":"1"}] via json.
You can use the code below, and it will display the json result back. Of course you will need to Connect to SQL to use below.
$query = " SELECT table_column_here ,COUNT(*) FROM table_name GROUP BY table_column_here; ";
$result = mysql_query( $query );
if ( !$result ) {
$ErrorMessage = 'Invalid query: ' . mysql_error() . "\n";
$ErrorMessage .= 'Whole query: ' . $query;
die( $ErrorMessage );
}
$JSON_output = array();
while ( $row = mysql_fetch_assoc( $result ) )
{
$JSON_output[] = array('column_name' => $row['column_name'],
'count' => $row['COUNT(*)'],
);
}
I would assume that it would be easier this route, but could be wrong :) Hope it helps you or someone else out :)
精彩评论