簡體   English   中英

PHP - 計算多維數組中第一個元素的唯一值

[英]PHP - count unique values in first element in multidimensional array

我有這個數組:

Array ( 
[0] => Array ( [0] => b [1] => d [2] => c [3] =>a [4] => ) 

[1] => Array ( [0] => c [1] => a [2] => d [3] => [4] => ) 

[2] => Array ( [0] => b [1] => d [2] => a [3] => [4] => )

[3] => Array ( [0] => a [1] => d [2] => c [3] =>b [4] => )

)

並且想要對每個內部數組的第一個元素中的唯一值執行計數。 在上面的例子中,一個有b中的2個,c中的1個和a中的1個。

我測試了這個:

$count = 0;
foreach ($the_outer_array as $key=>$value) {
    if ($value [0] == 'c') {
        $count++;
    }
}

但我一次只能檢查一個值。 想知道是否有一個外循環,“foreach(范圍('a','d')為$ i)”? 計數完成后,我希望將值存儲在一個數組中(即找到的字母和實例數)。

循環遍歷內循環中第一個元素的唯一值的任何建議? 再一次謝謝你!

使用array_key_exists並遞增計數,

$newArray = array();
foreach ($the_outer_array as $key=>$value) {
    $firstValue = $value[0];
    if ($foundKey = array_key_exists($firstValue,$newArray)) {
        $newArray[$firstValue] += 1;
    }
   else{
        $newArray[$firstValue] = 1;
   }
}

DEMO。

在php 5.5中有array_column() + array_count_values()

print_r(array_count_values(array_column($array, 0)));

例:

<?php
header('Content-Type: text/plain; charset=utf-8');

$array = [
    [ 'b', 'd', 'c', 'a' ],
    [ 'c', 'a', 'd', 'a' ],
    [ 'c', 'b', 'c', 'a' ]
];

print_r(array_count_values(array_column($array, 0)));
?>

結果:

Array
(
    [b] => 1
    [c] => 2
)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM