php编辑forloop里面的数组值

时间:2017-04-18 03:53:45

标签: php arrays

我有一个数组数组,我想循环它们,同时为每个数组分配一个新的键值。但原始阵列无法响应。这是我的尝试:

<?php
$cards = array(
    array(
        "test" => 1  
    ),array(
        "test" => 2      
    )
);

foreach($cards as $card){
    $card["success"] = 1;
}

print_r($cards);

输出:

Array
(
    [0] => Array
        (
            [test] => 1
        )

    [1] => Array
        (
            [test] => 2
        )

)

如何修改方法,因此可以在每个方法中插入“成功”值?

2 个答案:

答案 0 :(得分:3)

通过引用传递数组元素(注意&符号):

foreach($cards as &$card){
    $card["success"] = 1;
}

答案 1 :(得分:1)

你可以像这样使用它。这里我们在$key的迭代中插入值。

Try this code snippet here

<?php
ini_set('display_errors', 1);
$cards = array(
    array(
        "test" => 1  
    ),array(
        "test" => 2      
    )
);

foreach($cards as $key=> $card){
    $cards[$key]["success"] = 1;//Inserting value on the a key of $cards
}

print_r($cards);

<强>输出:

Array
(
    [0] => Array
        (
            [test] => 1
            [success] => 1
        )

    [1] => Array
        (
            [test] => 2
            [success] => 1
        )

)