2017-02-11 51 views
0

我有一個多維數組像下面,由多個列獲取獨特的數組 - PHP

,我想創建另一個陣列,顯示每個城市用戶的唯一編號

Array 
(
    [0] => Array 
     (
      [id] => 1 
      [city] => Melbourne 
      [date_added] => 1435852550 
      [user_name] => user_1 
     ) 

    [1] => Array 
     (
      [id] => 2 
      [city] => Melbourne 
      [date_added] => 1435852550 
      [user_name] => user_1 
     ) 

    [2] => Array 
     (
      [id] => 3 
      [city] => Sydeny 
      [date_added] => 1435852550 
      [user_name] => user_2 
     ) 

    [3] => Array 
     (
      [id] => 4 
      [city] => Perth 
      [date_added] => 1435852550 
      [user_name] => user_3 
     ) 
    [4] => Array 
     (
      [id] => 5 
      [city] => Perth 
      [date_added] => 1435852550 
      [user_name] => user_4 
     ) 
) 

我試圖搞定,用戶的唯一沒有每個城市像下面

Array 
(
    [Melbourne] => 1 
    [Sydeny] => 1 
    [Perth] => 2 
) 

回答

1

使用城市作爲指標,陣列USER_NAMES數組作爲值,則該值映射到值的lentgth。

foreach($array as $v) 
{ 
    $temp[$v['city']][$v['user_name']] = 1; 
} 
$result = array_map(function($v){return count($v);}, $temp); 
0

array_reduce使用功能的解決方案:

// $arr is your initial array 

$hash = []; 
$counts = array_reduce($arr, function($r, $a) use(&$hash){ 
    $hash_str = $a['city'] .'|'. $a['user_name']; 
    if (!in_array($hash_str, $hash)) { 
     $hash[] = $hash_str; 
     (!isset($r[$a['city']]))? $r[$a['city']] = 1 : $r[$a['city']] += 1; 
    } 
    return $r; 
}, []); 

print_r($counts);