PHP:如何在foreach中为数组增加价值

时间:2019-03-22 16:23:50

标签: php arrays foreach

我有以下数组:

$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中?

1 个答案:

答案 0 :(得分:1)

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

$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.
         ***/ 
    }
}

有很多可能的方法,具体取决于您对读取数据的方式设置了哪些限制。...