代码之家  ›  专栏  ›  技术社区  ›  AJK

PHP:如何在foreach[duplicate]中为数组添加值

  •  0
  • AJK  · 技术社区  · 6 年前

    我有以下数组:

    $cards = array();
    foreach($cardList as $card) {
      if ($card->getIsActive()) {
        $myValue = 'my_value';
        $cards[] = $card->getData(); // need to add $myValue to $card data
      }
    }
    
    $result = array(
        'cards' => $cards
    );
    echo json_encode($result);
    

    我怎样才能补充呢 $myValue $card->getData() 所以它出现在我的 $result ?

    0 回复  |  直到 6 年前
        1
  •  1
  •   Martin Miguel Stevens    6 年前

    一种方法是将值添加到对象的正确部分。

    $cards = [];
    foreach($cardList as $card) {
        if ($card->getIsActive()) {
            $myValue = 'my_value';
            /***
             * Add the data to the object
             ***/
            $card->addData($myValue);
            $cards[] = $card->getData(); // need to add $myValue to $card data
            /***
             * You do NOT need to remove this added data because $card is 
             * simply a COPY of the original object.
             ***/ 
        }
    }
    

    有很多可能的方法,这取决于你对如何读取数据有什么限制。。。。