2017-04-18 46 views
1

我有一个数组数组,我想循环它们,同时为每个指定一个新的键值。但原始数组无法响应。这里是我的尝试:php编辑内部forloop数组值

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

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

print_r($cards); 

OUTPUT:

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

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

) 

如何修改,因此“成功”的值可以插入到他们每个人的方法?通过引用

回答

3

传递数组元素(注意&符号):

foreach($cards as &$card){ 
    $card["success"] = 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 
     ) 

)