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
)
)
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)
);
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加