2011-04-20 56 views
1

我有一個包含一些陣列其他數組:在PHP中對數組中的唯一數組進行計數?

Array 
(
    [0] => Slip Object 
     (
      [userId:protected] => 1 
      [parentSlipId:protected] => 0 
      [id:protected] => 25 
      [madeDatetime:protected] => 2011-04-19 17:13:09 
      [stake:protected] => 34.00 
      [status:protected] => 6 
     ) 

    [1] => Slip Object 
     (
      [userId:protected] => 1 
      [parentSlipId:protected] => 0 
      [id:protected] => 25 
      [madeDatetime:protected] => 2011-04-19 17:13:09 
      [stake:protected] => 34.00 
      [status:protected] => 6 
     ) 

    [2] => Slip Object 
     (
      [userId:protected] => 1 
      [parentSlipId:protected] => 0 
      [id:protected] => 24 
      [madeDatetime:protected] => 2011-04-18 11:31:26 
      [stake:protected] => 13.00 
      [status:protected] => 6 
     )  
) 

有什麼獨特的計數陣列的最佳方式?

+4

您是否嘗試過'$獨特= array_unique($陣列,SORT_REGULAR);'? – biakaveron 2011-04-20 13:45:30

回答

3

了我的頭頂部,你可以嘗試:

$hashes = array(); 
$uniques = 0; 
foreach($array as $slip) { 
    $hash = sha1(serialize($slip)); 
    if(!in_array($hash, $hashes)) { 
     ++$uniques; 
     $hashes[] = $hash; 
    } 
} 
var_dump($uniques); // prints total number of unique objects. 

編輯: @ biakaveron的想法看起來雖好,可適應於:

$uniques = count(array_unique($array, SORT_REGULAR)); 
var_dump($uniques); // prints total number of unique objects. 
0

This previous question有不同的解決方案從數組中刪除重複的數組。如果你實現它們中的任何一個,然後在返回的數組上使用sizeof(),你將得到你的解決方案。

如:

<?php 
$yourarray = array(); 

$tmp = array(); 

foreach ($yourarray as $row) 
    if (!in_array($row,$tmp)) array_push($tmp,$row); 

echo sizeof($tmp); 
?> 
相關問題