2014-03-14 78 views
0

我處於一種情況下,通過子數組索引創建一個唯一的數組。請參閱此代碼並幫助我解決此問題。基於值的PHP數組唯一子數組

$user=Array(
     [1]=>Array(
       username => Sujith, 
       email=>[email protected], 
       [address] => Array(
        [address_id] => 1227 
        [city] => Ayoor 
        [state] => Kerala 
        [Country] => India 
       ) 
    ) 
    [2]=>Array(
     username => Ajith, 
     email=>[email protected], 
     [address] => Array(
      [address_id] => 1227 
      [city] => Ayoor 
      [state] => Kerala 
      [Country] => India 
     ) 
    ) 
    [3]=>Array(
     username => Akhil, 
     email=>[email protected], 
     [address] => Array(
      [address_id] => 1228 
      [city] => Kollam 
      [state] => Kerala 
      [Country] => India 
     ) 

    ) 
) 

我想讓它獨特的由address.address_id.So所得陣列應

$user=Array(
      [1]=>Array(
        username => Sujith, 
        email=>[email protected], 
        [address] => Array(
         [address_id] => 1227 
         [city] => Ayoor 
         [state] => Kerala 
         [Country] => India 
        ) 
     ) 
     [3]=>Array(
      username => Akhil, 
      email=>[email protected], 
      [address] => Array(
       [address_id] => 1228 
       [city] => Kollam 
       [state] => Kerala 
       [Country] => India 
      ) 

     ) 
    ) 

我的意思是,每address..Please 1個用戶幫我解決這個..

回答

-2

沒有本地的PHP函數做明確你想要什麼,但你可以: - 你自己的功能,這需要2分鐘 - 使用array_filter()

0
$tmpArray = array(); 
$newArr = array(); 
foreach($users as $user) 
{ 

if(!in_array($user['address']['address_id'],$tmpArray)) 
    $newArr[] = $user; 
$tmpArray[] = $user['address']['address_id'] 
} 
var_dump($newArr); 
1

通過$user陣列和unset()環路用戶,他們的address_id已經發生。

您可以使用輔助數組來跟蹤發生的address_id

$addresses = array(); 
foreach ($user as $key => $value) { 
    $id = $value['address']['address_id']; 
    if (in_array($id, $addresses)) { 
     unset($user[$key]); 
    } else { 
     $addresses[] = $id; 
    } 
} 
unset($addresses); 
+0

是的,這是它應該如何工作,因爲沒有內置的功能來執行操作。一起使用array_map和array_unique我們可以得到唯一的address_id,但這需要額外的循環來根據需要生成數組。此外,對於array_filter,您需要額外的循環來生成數組。所以,以簡單的方式,你的答案是相當不錯的! –

0
$unique_array = array(); 
    $address_id_accumulator = array(); 
    foreach ($user as $k => $v) {   
     if (!in_array($v['address']['address_id'], $address_id_accumulator)){ 
      $unique_array[$k] = $v; 
     } 
     $address_id_accumulator[] = $v['address']['address_id'];   
    } 

你的$用戶數組是這裏的輸入。 $ unique_array將是具有唯一地址標識的$ user數組。