[英]PHP changing value of item in a multidimensional array
I´ve already researched this, but the answers found did not solve my problem. 我已经对此进行了研究,但是找到的答案并不能解决我的问题。 I want to change all username items to 'kk', but printing the array afterwards show that nothing has been changed.
我想将所有用户名项目都更改为“ kk”,但是之后打印该数组表明没有任何更改。 What could be wrong?
有什么事吗
<?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);
It just gives me: 它给了我:
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
)
You should have done it that way: 您应该这样做:
foreach ($myArray as &$value)
{
$value['username'] = "kk";
}
Notice the & symbol. 注意&符号。 It gives you ability to change the array.
它使您能够更改阵列。
use the reference operator &
before the $value
in your loop to edit array row 在循环中的
$value
之前使用reference operator &
编辑数组行
References in PHP are a means to access the same variable content by different names.
PHP中的引用是通过不同名称访问相同变量内容的一种方式。 http://php.net/manual/en/language.references.whatare.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);
Make this way: 这样做:
foreach ($myArray as $key=>$value)
{
$myArray[$key]['username'] = "kk";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.