Chr*_*and 1 php foreach multidimensional-array array-push
我有一个从数据库查询构建的数组.根据数组中的值posuition,我需要为它分配另一个字符串.
我认为foreach循环中的if语句将是前进的方向,但我遇到了一些麻烦.
以下是我的代码......
$test = array(
array("test", 1),
array("test2", 2),
array("test4", 4),
array("test5", 5),
array("test3", 3),
array("test6", 6)
);
foreach($test as $t) {
if($t[1]==1){
array_push($t, "hello World");
}
}
print_r$test);
Run Code Online (Sandbox Code Playgroud)
除了array_push之外,其他所有接缝都可以工作.如果我在循环之后的print_r($ test)没有添加任何内容.
我在这里做了一些非常愚蠢的事吗?......
这是我得到的,如果我print_r($ test)
Array
(
[0] => Array
(
[0] => test
[1] => 1
)
[1] => Array
(
[0] => test2
[1] => 2
)
[2] => Array
(
[0] => test4
[1] => 4
)
[3] => Array
(
[0] => test5
[1] => 5
)
[4] => Array
(
[0] => test3
[1] => 3
)
[5] => Array
(
[0] => test6
[1] => 6
)
)
Run Code Online (Sandbox Code Playgroud)
我希望测试1在那里有一个名为"hello world"的第三个值
Foreach循环使用数组的副本.这就是为什么如果你想改变原始数组,你应该使用引用.
foreach($test as &$t) {
if($t[1]==1){
array_push($t, "hello World"); // or just $t[] = "hello World";
}
}
Run Code Online (Sandbox Code Playgroud)
不,你没有做任何有意义的愚蠢行为.但是如果$test要从foreach循环中更改数组,则必须将其作为引用传递.
foreach($test as &$t) // Pass by reference
{
if( $t[1] == 1 )
{
array_push($t, "hello World"); // Now pushing to $t pushes to $test also
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10550 次 |
| 最近记录: |