2017-07-12 86 views
0

我想輸出每個值出現在數組中的總次數。下面是我使用來獲取值的循環:計算每個值出現在數組中的次數(php)?

foreach($EM_Bookings as $EM_Booking){    
    $types = $EM_Booking->get_person()->dbem_types;      
} 

這裏是$types後續代碼var_dump所以你可以看到我想要統計數組:

string(2) "No" string(2) "No" string(3) "Yes" string(2) "No" string(2) "No" string(2) "No" string(14) "Not applicable" string(2) "No" string(2) "No" 

我要輸出每個唯一值的計數,這樣的:

  • 否= 7個
  • 是= 1
  • 不適用= 1

我知道我需要使用array_count_values,但我不知道如何將它與我的foreach循環相結合。我試圖乾脆這樣做:

$counts = array_count_values($types); 

但顯然這是不正確的。我需要以某種方式合併數組,然後數一數嗎?我還在學習,所以我不太明白我下一步需要做什麼。謝謝!

+0

是'$ types'字符串數組或者是它只是一個字符串? – Mic1780

+0

我認爲$ types是一個字符串數組。 (2)「否」字符串(2)「否」字符串(3)「是」字符串(2)'暗示它是一個字符串數組? – LBF

+0

在'foreach'和'$ types [] = $ EM_Booking ...'之前做'$ types = [];'並且它可以工作 – clover

回答

1

假設$types是一個字符串,這裏是我將如何跟蹤值的使用次數。

$typeCounter = array(); 
foreach ($EM_Bookings as $EM_Booking) { 
    $types = $EM_Booking->get_person()->dbem_types; 

    if (isset($typeCounter[$types]) === true) { 
     $typeCounter[$types]++; 
    } else { 
     $typeCounter[$types] = 1; 
    } 
} 

var_dump($typeCounter); 

如果$types是一個字符串數組,代碼應該是這樣的:

$typeCounter = array(); 
foreach ($EM_Bookings as $EM_Booking) { 
    $types = $EM_Booking->get_person()->dbem_types; 

    foreach ($types as $type) { 
     if (isset($typeCounter[$type]) === true) { 
      $typeCounter[$type]++; 
     } else { 
      $typeCounter[$type] = 1 
     } 
    } 
} 

var_dump($typeCounter); 
+0

嗚!你的第一個代碼工作。謝謝! – LBF

相關問題