我已经研究了这个,但找到的答案并没有解决我的问题。我想将所有用户名项更改为'kk',但之后打印数组显示没有任何更改。可能有什么不对?
<?php
$myArray = Array(
0 => Array(
'sender' => kk,
'message' => hhiui,
'timestamp' => '2017-02-04 10:04:57',
'username' => '',
'msgtype' => 0,
'threadid' => 20737047302042017230457
) ,
1 => Array(
'sender' => kk,
'message' => hhiui,
'timestamp' => '2017-02-04 10:04:57',
'username' => '',
'msgtype' => 0,
'threadid' => 20737047302042017230457
) ,
2 => Array(
'sender' => kk,
'message' => hhiui,
'timestamp' => '2017-02-04 10:04:57',
'username' => '',
'msgtype' => '16',
'threadid' => 20737047302042017230457
)
);
foreach($myArray as $value)
{
$value['username'] = "kk";
}
print_r($myArray);
它只是给了我:
Array
(
[0] => Array
(
[sender] => kk
[message] => hhiui
[timestamp] => 2017-02-04 10:04:57
[username] =>
[msgtype] => 0
[threadid] => 2.0737047302042E+22
)
[1] => Array
(
[sender] => kk
[message] => hhiui
[timestamp] => 2017-02-04 10:04:57
[username] =>
[msgtype] => 0
[threadid] => 2.0737047302042E+22
)
[2] => Array
(
[sender] => kk
[message] => hhiui
[timestamp] => 2017-02-04 10:04:57
[username] =>
[msgtype] => 16
[threadid] => 2.0737047302042E+22
)
)
Array
(
[2] => Array
(
[sender] => kk
[message] => hhiui
[timestamp] => 2017-02-04 10:04:57
[username] =>
[msgtype] => 16
[threadid] => 2.0737047302042E+22
)
答案 0 :(得分:3)
你应该这样做:
foreach ($myArray as &$value)
{
$value['username'] = "kk";
}
注意&amp;符号。它使您能够更改阵列。
答案 1 :(得分:2)
使用循环中reference operator &
之前的$value
来编辑数组行
PHP中的引用是一种访问相同变量内容的方法 不同的名字。 http://php.net/manual/en/language.references.whatare.php
<?php
$myArray = Array(
0 => Array(
'sender' =>"kk",
'message' => "hhiui",
'timestamp' => '2017-02-04 10:04:57',
'username' => '',
'msgtype' => 0,
'threadid' => 20737047302042017230457
) ,
1 => Array(
'sender' => "kk",
'message' => "hhiui",
'timestamp' => '2017-02-04 10:04:57',
'username' => '',
'msgtype' => 0,
'threadid' => 20737047302042017230457
) ,
2 => Array(
'sender' => "kk",
'message' => "hhiui",
'timestamp' => '2017-02-04 10:04:57',
'username' => '',
'msgtype' => '16',
'threadid' => 20737047302042017230457
)
);
foreach($myArray as &$value)
{
$value['username'] = "kk";
}
print_r($myArray);
答案 2 :(得分:1)
这样做:
foreach ($myArray as $key=>$value)
{
$myArray[$key]['username'] = "kk";
}