【问题标题】:How to set php array index as array value...?如何将php数组索引设置为数组值...?
【发布时间】:2017-10-26 07:13:48
【问题描述】:

我从查询中得到了这个数组。

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
        )
)

我需要将 array index 设置为 array value (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 是唯一值,不会重复。无需担心索引值。

如何将该数组转换为指定的索引值..?

【问题讨论】:

  • @ThisGuyHasTwoThumbs 我认为他想要 laravel 所说的 keyBy
  • @apokryfos 啊我明白了 - 删除了评论:)

标签: php arrays multidimensional-array indexing


【解决方案1】:

这正是array_column() 的用途:

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

array_column() 从输入的单个列返回值,由 column_key 标识。 可选地,可以提供一个 index_key 来根据输入数组的 index_key 列中的值对返回数组中的值进行索引。

column_key

要返回的值列。此值可能是您希望检索的列的整数键,也可能是关联数组或属性名称的字符串键名称。 返回完整的数组或对象也可以为 NULL(这与 index_key 一起用于重新索引数组)。

【讨论】:

  • 每天使用这个漂亮的函数,第一次尝试将第二个参数传递为null :)
【解决方案2】:

你可以试试这段代码,这里我做了一些额外的工作。请参阅AbraCadaver's clever answer $result = array_column($array, null, 'user_id');

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

【讨论】:

  • 聪明。我总是最终使用循环。不错的组合!
  • 出于好奇-我在文档中没有看到-但是您是否理解array_column 保留了顺序?这对于它的工作是必要的。
  • @是的,我试过了。我认为这里的 php 可能是使用迭代器来获取它。
  • 为什么是array_combine()? array_column() 的第三个参数就是这样做的。
  • @AbraCadaver 好方法。我从来没有注意到它。谢谢。
【解决方案3】:

这两种结构都过于复杂和多余。为什么不

$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;

【讨论】:

    猜你喜欢
    • 2013-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多