array_push在foreach循环中不起作用

时间:2014-05-22 09:56:53

标签: php arrays loops array-push

print_r($members)如下结果

Array ( [myname] => Array ( [userid] => 52 [age] => 46 )
Array ( [hisname] => Array ( [userid] => 22 [age] => 47 )
Array ( [yourname] => Array ( [userid] => 47 [age] => 85 )

array_push()推送不在foreach循环中

foreach($members as $key => $item){
  // print "<br>" . $key ."<br>";
  array_push($members, '$key');
}

结果需要使用array_push()

以下代码
Array ( [myname] => Array ( [userid] => 52 [age] => 46 [0] => myname)
Array ( [hisname] => Array ( [userid] => 22 [age] => 47 [0] => hisname)
Array ( [yourname] => Array ( [userid] => 47 [age] => 85 [0] => yourname)

结果

警告:array_push()期望参数1为数组,在第126行的C:\ xampp \ htdocs \ index.php中给出null

警告:array_push()期望参数1为数组,在第126行的C:\ xampp \ htdocs \ index.php中给出null

警告:array_push()期望参数1为数组,在第126行的C:\ xampp \ htdocs \ index.php中给出null

1 个答案:

答案 0 :(得分:5)

因为$arr似乎不是一个数组。将您的代码更改为,

foreach($members as $key => $item){
   array_push($members[$key], $key); //or $members[$key][] = $key;
}