2017-05-25 143 views
0

我從查詢中得到這個數組。如何將php數組索引設置爲數組值...?

Array 
(
    [0] => Array 
     (
      [user_id] => 5 
      [first_name] => Diyaa 
      [profile_pic] => profile/user5.png 
     ) 

    [1] => Array 
     (
      [user_id] => 8 
      [first_name] => Raj 
      [profile_pic] => profile/user8.jpg 
     ) 

    [2] => Array 
     (
      [user_id] => 10 
      [first_name] => Vanathi 
      [profile_pic] => profile/user10.jpg 
     ) 
) 

我需要設置數組索引數組值user_id)如下面給出:

Array 
(
    [5] => Array 
     (
      [user_id] => 5 
      [first_name] => Diyaa 
      [profile_pic] => profile/user5.png 
     ) 

    [8] => Array 
     (
      [user_id] => 8 
      [first_name] => Raj 
      [profile_pic] => profile/user8.jpg 
     ) 

    [10] => Array 
     (
      [user_id] => 10 
      [first_name] => Vanathi 
      [profile_pic] => profile/user10.jpg 
     ) 
) 

注:user_id是一個唯一的值,也不會重複再次。無需擔心索引值。

如何轉換並獲取該數組作爲指定的索引值..?

+1

@ThisGuyHasTwoThumbs我想他想要什麼laravel調用['keyBy'](https://laravel.com/docs/5.4/collections#method-keyby) – apokryfos

+0

@apokryfos啊我看到 - 刪除評論:) – ThisGuyHasTwoThumbs

回答

4

你可以試試這段代碼,在這裏我做了一些額外的工作。參考AbraCadaver's clever answer $result = array_column($array, null, 'user_id');

array_combine(array_column($array, 'user_id'), $array); 
+1

聰明。我總是最終使用循環。好的組合! –

+0

出於好奇 - 我沒有在文檔中看到它 - 但你的理解是'array_column'保留了順序?這對於這項工作是必要的。 –

+0

@yes,我試過了。我想這裏的PHP可能會使用迭代器來獲取它。 –

4

這正是array_column()爲:

$result = array_column($array, null, 'user_id'); 

array_column()從輸入的單個列,由column_key確定返回值。 可選地,可以提供index_key以通過來自輸入數組的index_key列的值來索引返回數組中的值。

column_key

值返回的列中。該值可能是您希望檢索的列的整數鍵,也可能是關聯數組或屬性名稱的字符串鍵名稱。 它也可能是NULL來返回完整的數組或對象(這與index_key一起用於重新索引數組)。

+2

每天使用這個漂亮的功能,第一次嘗試通過第二個參數爲空:) – hassan

0

這兩種結構都是不必要的複雜和冗餘。爲什麼不

$foo = array(5 => 
      array('first_name' => 'Diyaa', 
       'profile_pic' => 'profile/user5.png'), 
      8 => 
      array('first_name' => 'Raj', 
       'profile_pic' => 'profile/user8.png'), 
      ... 
      ); 

然後通過$foo[$user_id]訪問它,它會給你一個2元關聯數組如

  array('first_name' => 'Raj', 
       'profile_pic' => 'profile/user8.png'), 

對於改變profile_pic:

$foo[$user_id]['profile_pic'] = $new_pic;