在foreach中有条件地将元素添加到数组中

ben*_*wad 0 php arrays

我目前有这个代码用于填充要返回的注释列表:

foreach ($comments as $comment)
{
    $f_comments[] = array (
        'comment_id'    => $comment['comment_id'],
        'comment_body'  => $comment['comment_body'],
        'user_id'       => $comment['user_id'],
        'user_avatar'   => $comment['user_avatar'],
        'user_username' => $comment['user_username'],
        'timeago'       => formatter_common_format_time_string($comment['added']),
    );

    if (!empty($comment['user_picture']))
    {
        $f_comments[]['user_picture'] = $comment['user_picture'];
    }
}
Run Code Online (Sandbox Code Playgroud)

问题是,这是返回的内容:

"comments":[{"comment_id":9386,"comment_body":"Comment","user_id":46542,"user_avatar":"9","user_username":"TestUser","timeago":"about 2 hours ago"},{"user_picture":"ec237f517bc26b27d8e790c3a5d125841321552075"}]
Run Code Online (Sandbox Code Playgroud)

...而我希望user_picture与其他结果一起使用,如下所示:

[{"comment_id":9386,"comment_body":"Comment","user_id":46542,"user_avatar":"9","user_username":"TestUser","timeago":"about 2 hours ago", "user_picture":"ec237f517bc26b27d8e790c3a5d125841321552075"}]
Run Code Online (Sandbox Code Playgroud)

......但是我看不到这样做的方法.我对PHP很陌生,所以我可能会遗漏一些明显的东西.任何人都可以看到什么是错的?

SER*_*PRO 5

添加您的评论索引:

foreach ($comments as $i => $comment)
{
    $f_comments[$i] = array (
        'comment_id'    => $comment['comment_id'],
        'comment_body'  => $comment['comment_body'],
        'user_id'       => $comment['user_id'],
        'user_avatar'   => $comment['user_avatar'],
        'user_username' => $comment['user_username'],
        'timeago'       => formatter_common_format_time_string($comment['added']),
    );

    if (!empty($comment['user_picture']))
    {
        $f_comments[$i]['user_picture'] = $comment['user_picture'];
    }
}
Run Code Online (Sandbox Code Playgroud)

或者只是创建一个变量$ i = 0; 在foreach之前,在你关闭之前增加它$ i ++;