$userDatas = [ ['user_id'=>1], ['user_id'=>3] ]; $userIds = []; foreach ($userDatas as $item){ $userIds[] = $item['user_id']; } halt($userIds); return $userIds;
输出: array(2) { [0] => int(1) [1] => int(3)} 如果将$userId[] 改为 $userId:
$userDatas = [ ['user_id'=>1], ['user_id'=>3] ]; $userIds = []; foreach ($userDatas as $item){ $userIds = $item['user_id']; } halt($userIds); return $userIds;
输出:
int(3)
分析:去掉[],$userIds 视为变量,等于循环给变量赋值,第一次循环给变量赋值为1,第二次循环又给变量赋值为3,替换掉了1,所以输出:3