doujiao2443 2018-05-08 18:44
浏览 42
已采纳

从foreach值创建嵌套关联数组

I'm trying to create associative nested array from foreach values, but not sure how to get it in desired format, as right now associative array is getting wrapped with numeric one.

I understand it's because shouldn't use array() to wrap values, but not sure how to do it right.

$arr=array();

foreach ($all_users as $val) {
   $arr[] = array( $val->data->user_nicename => array(
    'username'=> $val->data->display_name,
    'avatar_url' => get_avatar_url($val->ID)
    )
    );
}

print_f($arr);

Getting array result like this:

Array
(
   [0] => Array
       (
           [john_s] => Array
               (
                [username] => John Smith
                [avatar_url] => https://secure.gravatar.com
            )

    )

[1] => Array
    (
        [sarah_s] => Array
            (
                [username] => Sarah Smith
                [avatar_url] => https://secure.gravatar.com
            )

    )
)

While desired format is this:

Array
(
    [john_s] => Array
        (
            [username] => John Smith
            [avatar_url] => https://secure.gravatar.com
        )
    [sarah_s] => Array
        (
            [username] => Sarah Smith
            [avatar_url] => https://secure.gravatar.com
        )
)
  • 写回答

3条回答 默认 最新

  • dongwu9170 2018-05-08 18:47
    关注

    You are nesting one level too deep:

    <?php
    $arr=array();
    
    foreach ($all_users as $val) {
    
        // Use $val->data->user_nicename as the index to build an associative array of the other data
        // This assumes that user_nicename is unique throughout the loop
        // If you have multiple users with the same user_nicename then some data can get "lost"
        $arr[$val->data->user_nicename] = array(
            'username'=> $val->data->display_name,
            'avatar_url' => get_avatar_url($val->ID)
        );
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥100 数字取证课程 关于FAT文件系统的操作
  • ¥15 如何使用js实现打印时每页设置统一的标题
  • ¥15 安装TIA PortalV15.1报错
  • ¥15 能把水桶搬到饮水机的机械设计
  • ¥15 Android Studio中如何把H5逻辑放在Assets 文件夹中以实现将h5代码打包为apk
  • ¥15 使用小程序wx.createWebAudioContext()开发节拍器
  • ¥15 关于#爬虫#的问题:请问HMDB代谢物爬虫的那个工具可以提供一下吗
  • ¥15 vue3+electron打包获取本地视频属性,文件夹里面有ffprobe.exe 文件还会报错这是什么原因呢?
  • ¥20 用51单片机控制急停。
  • ¥15 孟德尔随机化结果不一致