0

I have the following array:

$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);

How would I be able to add $myValue to $card->getData() so it appears in my $result ?

AJK
  • 391
  • 9
  • 27
  • How exactly is this question a duplicate of that question? – Martin Mar 22 '19 at 16:30
  • Because they are asking how to parse JSON with PHP @Martin – Jay Blanchard Mar 22 '19 at 16:32
  • @JayBlanchard I edited my question a little bit to hopefully clear it up. I can parse the JSON, I'm more asking how to add a value to an existing array of data so it can be parsed by json. – AJK Mar 22 '19 at 16:34
  • You could push it into the array. – Jay Blanchard Mar 22 '19 at 16:36
  • 2
    Basically what you need to is: `$card['my_value'] = $myValue` inside of the loop – Bruno Francisco Mar 22 '19 at 16:37
  • Be aware that changing `$card` itself won't change `$cardlist` – Romain B. Mar 22 '19 at 16:38
  • @Charlie Thank you, that was exactly what I was looking for. – AJK Mar 22 '19 at 16:48
  • @JayBlanchard the OP was ***NOT*** asking how to parse JSON with PHP. The fact JSON appears anywhere in the code is co-incidental. They are asking how to add values to a dataset inside a loop. – Martin Mar 22 '19 at 16:59
  • In the original question, *"How would I be able to retrieve my_value from card data from my $result ?"* they appeared to ask how to retrieve the value from the JSON. The question has been edited since then and I will reopen. @Martin – Jay Blanchard Mar 22 '19 at 17:01
  • We delve into the underwhelming world of schemantics here: I read the original version of the question but still understood that while the question was superficially asking *"how to read"* that due to the code-block in the question, it was *actually* asking "how to write". Anyway... – Martin Mar 22 '19 at 17:07

1 Answers1

1

One method is to add the value to the correct part of the object.

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

There are lots of possible method, depending on what restrictions you have in place for how you can read the data....

Martin
  • 22,212
  • 11
  • 70
  • 132
  • Thanks! I ended up adding `$card['my_value'] = $myValue` before `$card->getData()` , but this worked as well! – AJK Mar 22 '19 at 17:22