1

I have an array built from a database query. Based on the values posuition with the array I need to assign another string to it.

I thought an if statement within a foreach loop would be the way forward but I'm having some trouble.

Below is my code......

$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);

Everything seams to work other than the array_push. If i print_r($test) after the loop nothing has been added.

Am I doing something monumentally stupid here?...

This is what I get if i 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
    )

)

I would be expecting test 1 to have a 3rd value in there called "hello world"

4

2 回答 2

5

Foreach 循环使用数组的副本。这就是为什么如果你想改变原始数组,你应该使用引用。

foreach($test as &$t) {
   if($t[1]==1){
      array_push($t, "hello World"); // or just $t[] = "hello World";
   }
}
于 2012-08-17T09:10:21.660 回答
5

不,你没有做任何非常愚蠢的事情。但是,如果您想$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
    }
}
于 2012-08-17T09:11:04.627 回答