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

Row*_*wan 2 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
  )
)
Run Code Online (Sandbox Code Playgroud)

如果适用,这是我用来请求和解密它的php

$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>';
}
Run Code Online (Sandbox Code Playgroud)

pea*_*man 7

使用此count功能$persons可获取项目数.


Jam*_*mes 5

这应该可以解决问题。

$iCount = count($persons)
Run Code Online (Sandbox Code Playgroud)

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

目前您得到的是所谓的 astdClass但如果您truejson_decode函数添加参数,您将得到一个普通数组。不管是否使用true参数,你仍然可以调用count:)

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

你去吧:)