如何在数组中添加新项

时间:2013-01-10 08:31:00

标签: php arrays

这是我用PHP打印的数组

Array ( [0] => Array ( [friend_id] => 1 [name] => parker[email] => parker@gmail.com)[1] => Array ( [friend_id] => 2 [name] => peter [email] => peter@hotmail.com) )

我可以知道如何在php中使用循环在数组中添加一个新项目/参数

Array ( [0] => Array ( [friend_id] => 1 [name] => parker[email] => parker@gmail.com [NEWOBJECT] => newvalue)[1] => Array ( [friend_id] => 2 [name] => peter [email] => peter@hotmail.com [NEWOBJECT] => newvalue) )

2 个答案:

答案 0 :(得分:1)

不需要循环,你可以这样添加:

<?
 $arr =  Array ( [0] => Array ( [friend_id] => 1 [name] => parker[email] => parker@gmail.com)[1] => Array ( [friend_id] => 2 [name] => peter [email] => peter@hotmail.com) );

 $arr[0]['NEWOBJECT'] = 'blablabla';
 $arr[1]['NEWOBJECT'] = 'blablabla';
?>

但是当你必须这样做超过2次时,这会有所帮助:

<?

$arr =  Array ( [0] => Array ( [friend_id] => 1 [name] => parker[email] => parker@gmail.com)[1] => Array ( [friend_id] => 2 [name] => peter [email] => peter@hotmail.com) );

 foreach($arr as $key => $value){
    $arr[$key]['NEWOBJECT'] = 'blablabla';
 }

?>

答案 1 :(得分:0)

您可以使用foreach loop来迭代项目,并按以下方式添加新密钥。

foreach($array as &$item) {
    $item['newkey'] = "New Value";
}

请注意使用&号(&amp;)运算符。这可以确保我们引用$ item而不是副本,这意味着更改将影响原始$ item。