Php 如何创建每个数据数组并将数据输入数组子项$arrayTw?
我在变量$tw中有数据数组,我想在新数组子对象中操作值$tw,下面是我的代码:Php 如何创建每个数据数组并将数据输入数组子项$arrayTw?,php,arrays,Php,Arrays,我在变量$tw中有数据数组,我想在新数组子对象中操作值$tw,下面是我的代码: static public function getTrackTwitter($hashtag, $media) { $tw = Twitter::getSearch(['q' => $hashtag, 'count' => 100, 'result_type' => 'mixed', 'until' => '', 'format' => 'array']);
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个数据?为什么不循环数据?您需要在每次迭代中创建一个新的数组元素(使用
[]
),而不是覆盖$arrayTw
变量。然后在循环后返回:
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;
}
你在循环的中间返回,所以函数将返回$ARATYTW;在您的foreach}结束后,它是try-put-return$arrayTw;在foreach结束后,但相同的数据仅打印1个