Aivaras
Aivaras

Reputation: 125

Create nested associative array from foreach values

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

Upvotes: 1

Views: 655

Answers (3)

Praveen
Praveen

Reputation: 642

When you use $arr[] it will create numeric array location and increments the location each time it executes in the loop. If you want to create an associative array then you have to add the associative array key in the bracket [], in this case it would be $val->data->user_nicename. Just a small change needed in your code as below,

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

print_f($arr);

Upvotes: 0

Pipe
Pipe

Reputation: 2424

Then do:

$arr=array();

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

print_f($arr);

You need to create a key in the original array, not append another array to it.

Upvotes: 0

MonkeyZeus
MonkeyZeus

Reputation: 20737

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

Upvotes: 5

Related Questions