2017-08-31 193 views
2

我有一個這樣的數組。 (例如變量名稱是$ arr)php - 基於元素數組的條件

[ 
1 => [ 
    'A' => '1' 
    'C' => 'TEMU3076746' 
] 
2 => [ 
    'A' => '2' 
    'C' => 'FCIU5412720' 
] 
3 => [ 
    'A' => '3' 
    'C' => 'TEMU3076746' 
] 
4 => [ 
    'A' => '4' 
    'C' => 'TEMU3076746' 
] 
5 => [ 
    'A' => '5' 
    'C' => 'FCIU5412720' 
] 
] 

我的目標是對元素數組進行基於計數的條件。

總元素所有數組可能是這樣的:count($ arr)。這是5.

但是,如何計算基於'C'元素,但不重複。 如果你能看到,C元素是基於C

'TEMU3076746, FCIU5412720' 

所以總元件2

請告知

回答

2

結合array_maparray_uniquecount

$array = [ /* your array */ ]; 
$count = count(
    array_unique(
     array_map(function($element) { 
      return $element['C']; 
     }, $array)))) 

或使用array_column正如sahil gulati所建議的那樣,array_map可以做更多的事情h可能在這裏不需要。

5

希望這個最簡單的將有所幫助。這裏我們使用的是array_column,array_uniquecount

Try this code snippet here

echo count(
     array_unique(
       array_column($data,"C"))); 

結果:2

+2

TIL array_column存在例如... – Jakumi

+2

@Jakumi歡迎朋友。 。:) –

+2

只是說,也可以在'array_unique'處使用'array_flip'。 +1 – Thamilan

0

我有一個非常類似的需要,我用一個稍微不同的方法。

我有幾個參賽隊參加的比賽,我需要知道每個比賽有多少隊。換句話說,我不需要知道有多少不同的項目「C」,但有多少項目TEMU3076746FCIU5412720。然後

的代碼如下是

$nbCs = array_count_values (array_column ($array, 'C')); 

$nbCs將發行values = Array([TEMU3076746] => 3 [FCIU5412720] => 2)

數組見沙箱Sandbox code