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

报告相同问题?