从foreach值

时间:2018-05-08 18:44:19

标签: php arrays associative-array

我正在尝试使用foreach值创建关联嵌套数组,但不确定如何以所需格式获取它,因为现在关联数组正在用数字值包装。

我理解这是因为不应该使用array()来包装值,但不确定如何正确执行。

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

获取这样的数组结果:

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
            )

    )
)

虽然所需的格式是:

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 个答案:

答案 0 :(得分:4)

你正在将一个级别嵌套太深:

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

答案 1 :(得分:0)

然后做:

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

您需要在原始数组中创建一个键,而不是向其附加另一个数组。

答案 2 :(得分:0)

使用$ arr []时,它将创建数值数组位置,并在每次循环执行时递增位置。如果要创建关联数组,则必须在括号[]中添加关联数组键,在这种情况下,它将是$ val-&gt; data-&gt; user_nicename。只需在代码中进行一些小改动,如下所示,

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