PHP计数JSON请求中返回的项目数?

时间:2011-05-07 18:30:09

标签: php json

我正在寻找一种方法来计算在搜索数据库时获得的这些JSON字符串中返回的项目数(以PHP为单位)。

请原谅我,因为我完全废弃了这一切。

我被告知因为JSON版本中没有返回计数,就像这个数据库中的XML一样,我将不得不使用循环来计算结果数量?

我已经环顾四周,但似乎没有什么比我想做的更合适了......

以下是我得到的字符串示例:

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

如果适用的话,这是我用来请求&破译它

$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>';
}

3 个答案:

答案 0 :(得分:7)

使用$persons上的count功能获取商品数量。

答案 1 :(得分:4)

这应该可以解决问题。

$iCount = count($persons)

当您调用json_decode时,您将获得一个PHP变量,其中包含一系列项目和值。

目前您正在获得所谓的stdClass,但如果您向true函数添加json_decode参数,则会获得正常数组。虽然使用了true参数,但您仍然可以调用count:)

$name = $_GET['search'];
$persons_result = $tmdb->searchPerson($name);
$persons = json_decode($persons_result, true);
print_r($persons);

你去:)

答案 2 :(得分:-1)

如果您运行与下面相同的查询,它将返回项目,并计算唯一项目

$query = " SELECT table_column_here ,COUNT(*) FROM table_name GROUP BY table_column_here;  ";

将通过json返回[{&#34; column_name&#34;:&#34; column_data_result&#34;,&#34; count&#34;:&#34; 1&#34;}]。

您可以使用下面的代码,它将显示json结果。当然,您需要连接到SQL才能在下面使用。

$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(*)'],
                        );
    }

我认为这条路线会更容易,但可能是错误的:)希望它可以帮助你或其他人:)

相关问题