2011-05-07 132 views
2

我正在尋找一種方法來計算在搜索數據庫時所獲得的這些JSON字符串中返回的項目數量(以PHP爲單位)。在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 
) 
) 

及(如適用)這裏是我用來請求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>'; 
} 
+3

是否有某種原因,['count'(HTTP: //php.net/manual/en/function.count.php)不起作用? – sdleihssirhc 2011-05-07 18:32:34

回答

7

使用上$personscount函數來獲取項目的數量。

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

你去那裏:)

-1

如果您運行相同的下方將返回項目的查詢,統計和獨特的項目

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

哪個會通過json返回[{「column_name」:「column_data_result」,「count」:「1」}]]。

您可以使用下面的代碼,它會顯示返回的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(*)'], 
         ); 
    } 

我認爲它會更容易些這條路線,但可能是錯誤的:)希望它可以幫助你或其他人了:)