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

时间:2011-11-18 11:57:59

标签: 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'];
    }
}

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

"comments":[{"comment_id":9386,"comment_body":"Comment","user_id":46542,"user_avatar":"9","user_username":"TestUser","timeago":"about 2 hours ago"},{"user_picture":"ec237f517bc26b27d8e790c3a5d125841321552075"}]

...而我希望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"}]

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

1 个答案:

答案 0 :(得分: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'];
    }
}

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