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 ?

10
  • How exactly is this question a duplicate of that question? Commented Mar 22, 2019 at 16:30
  • Because they are asking how to parse JSON with PHP @Martin Commented Mar 22, 2019 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. Commented Mar 22, 2019 at 16:34
  • You could push it into the array. Commented Mar 22, 2019 at 16:36
  • 2
    Basically what you need to is: $card['my_value'] = $myValue inside of the loop Commented Mar 22, 2019 at 16:37

1 Answer 1

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....

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I ended up adding $card['my_value'] = $myValue before $card->getData() , but this worked as well!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.