[英]list and count elements in array php
我有以下數組,並試圖用php遍歷它,生成“類型”列表並計算數量。 “類型”是關鍵,但是會有唯一的值,例如“呼叫”,“待辦事項”,“會議”,“提案”等。我的目標是提供以下各項:
Call 2
To-do 1
Meeting 3
Proposal 4
上面的不是從以下數組輸出的值,但是我希望您對我要完成的事情有所了解。 請幫忙!
Array (
[0] => Array (
[0] => Call
[Type] => Call
[1] => fxxxx@xxxxentllc.com
[EmailAddress] => xxxxr@xxxxentllc.com
[2] => 3xxxx00
[Phone] => 31xxxx00
[3] => 31xxxx871
[MobilePhone] => 31xxxx871
[4] => 102795
[CustomerID] => 102795
[5] => Nortxxxxal
[Company] => Noxxxxal
[6] => Frank
[FirstName] => Frank
[7] => Syxxxxer
[LastName] => Sxxxxter
[8] => 3
[Priority] => 3
[9] => invite to Haxxxxales for lunch
[Details] => invite to Hafxxxxales for lunch
[10] => 4503
[ActivityID] => 4503
[11] => 05/23/13
[DueDate] => 05/23/13
)
[1] => Array (
[0] => To-do
[Type] => To-do
[1] => fsxxxxer@summxxxxntllc.com
[EmailAddress] => fsxxxxer@summixxxxtllc.com
[2] => 315xxxx000
[Phone] => 3154xxxx0
[3] => 315xxxx1
[MobilePhone] => 315xxxx1
[4] => 102795
[CustomerID] => 102795
[5] => Norxxxxl
[Company] => Norxxxxcal
[6] => Frxxxxk
[FirstName] => Fxxxxk
[7] => Sxxxxr
[LastName] => Syxxxxer
[8] => 3
[Priority] => 3
[9] => find out who contact is for xxxxdical center
[Details] => find out who contact is foxxxxcal center
[10] => 4504
[ActivityID] => 4504
[11] => 05/23/13
[DueDate] => 05/23/13
)
)
應該這樣做:
$type_counts = array_count_values(array_map(function($x) {return $x['Type'];}, $array));
array_map
將返回一個包含所有Type
元素的數組,然后array_count_values
將計算每個元素的數量並將其作為關聯數組返回。
類似於以下內容:
foreach ($array as $key => $value) {
if (isset($result[$key])) {
$result[$key]++;
} else {
$result[$key] = 1;
}
}
如果它是多維數組,則在其中每個數組都放一個,但這應該可以給你一個思路
$types = array();
foreach($array as $item) {
isset(${$item['Type']}) ? ${$item['Type']}++ : ${$item['Type']} = 1;
if(!in_array($item['Type'], $types) {
$types[] = $item['Type'];
}
foreach($types as $type) {
echo "$type ${$type}\n";
}
我認為您可以循環使用數組並計算每次出現的次數
$Call = 0;
$To_do = 0;
$Meeting = 0;
$Proposal = 0;
foreach($array as $data)
{
if($data['Type'] == 'Call')
{
$Call++;
} else if($data['Type'] == 'To-do')
{
$To_do++;
} else if($data['Type'] == 'Meeting')
{
$Meeting++;
} else if($data['Type'] == 'Proposal')
{
$Proposal++;
}
}
這樣,您將在每個變量$Call $To_do $Meeting $Proposal
其相對計數
您可以使用(array_count_values($ array)); http://php.net/manual/en/function.array-count-values.php這給出了數組中所有鍵的計數。
如果只需要特定的鍵,則使用foreach循環
提到的一種Petros是最好的方法。
我會按照以下方式做一些事情:
$your_array = /* Your Array */
$types_count = array();
foreach ($your_array as $type_array){
$types_count[$type_array['Type']]++;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.