dongyu9894
2017-04-18 03:53 浏览 8
已采纳

php编辑for循环中的数组值

I have an array of arrays, and I want to loop them while assigning a new key-value for each. But the original array fails to response. Here is my try:

<?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
        )

)

How can I modify the method hence the 'success' value can be inserted into each of them?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答 默认 最新

  • 已采纳
    duanlingzei0170 duanlingzei0170 2017-04-18 03:56

    Passing array elements by reference (notice the & sign):

    foreach($cards as &$card){
        $card["success"] = 1;
    }
    
    点赞 评论 复制链接分享
  • doushaqing7080 doushaqing7080 2017-04-18 03:57

    You can use it like this. Here we are inserting value on the iteration of $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);
    

    Output:

    Array
    (
        [0] => Array
            (
                [test] => 1
                [success] => 1
            )
    
        [1] => Array
            (
                [test] => 2
                [success] => 1
            )
    
    )
    
    点赞 评论 复制链接分享

相关推荐