2017-05-25 146 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;