如何foreach数据数组并输入数据到数组$ arrayTw?

时间:2018-08-21 15:22:37

标签: php arrays

我在变量$ tw中有数据数组,我想在新数组子元素中操纵值$ tw,这是我的代码:

static public function getTrackTwitter($hashtag, $media)
{

        $tw = Twitter::getSearch(['q' => $hashtag, 'count' => 100, 'result_type' => 'mixed', 'until' => '', 'format' => 'array']);
        foreach ($tw['statuses'] as $key => $value) {
            // $date       = date('M d',strtotime($value['created_at']));

            $arrayTw = array(
                'caption' => $value['text'],
                'code'    => $value['id'],
                // 'created' => $date,
                'user'    => $value['user']['screen_name'],
                'user_img'=> $value['user']['profile_image_url'],
                'likes'   => $value['favorite_count'],
                'comments'=> $value['retweet_count'],
                'engage'  => $value['favorite_count'] + $value['retweet_count'],
                'media'   => 'tw'
            );
            return $arrayTw;
        }

}

为什么返回$ arrayTw只打印1个数据?为什么不循环数据?

1 个答案:

答案 0 :(得分:1)

您需要在每次迭代中创建一个新的数组元素(使用[]),而不是覆盖$arrayTw变量。然后在循环后return

static public function getTrackTwitter($hashtag, $media)
{
    $tw = Twitter::getSearch(['q' => $hashtag, 'count' => 100, 'result_type' => 'mixed', 'until' => '', 'format' => 'array']);

    foreach ($tw['statuses'] as $key => $value) {
        // $date       = date('M d',strtotime($value['created_at']));
        $arrayTw[] = array(
            'caption' => $value['text'],
            'code'    => $value['id'],
            // 'created' => $date,
            'user'    => $value['user']['screen_name'],
            'user_img'=> $value['user']['profile_image_url'],
            'likes'   => $value['favorite_count'],
            'comments'=> $value['retweet_count'],
            'engage'  => $value['favorite_count'] + $value['retweet_count'],
            'media'   => 'tw'
        );
    }
    return $arrayTw;
}