0

这是我用 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) )
4

2 回答 2

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';
 }

?>
于 2013-01-10T08:37:51.710 回答
0

您可以使用foreach 循环以下列方式遍历项目并添加新键。

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

请注意与 (&) 运算符的使用。这确保了我们对 $item 的引用而不是副本,这意味着更改将影响原始 $item。

于 2013-01-10T08:38:48.667 回答