skip to Main Content

I want to create new object keys in foreach loop so I write:

$all_variants = $p->variants;
        foreach ($all_variants as $a) {
                $a->discount_price = $a->price;
                $a->original_price = $a->price;
                $a->button_text = 'BUY';
           
        }

but this code wont create new keys (discount_price, original_price, button_text) … $all_variants->discount_price is undefinded ….
Whats bad in my code?

3

Answers


  1. Chosen as BEST ANSWER

    This works for me:

    foreach ($p->variants as $a) {
                    $a['discount_price'] = $a['price'];
                    $a['original_price'] = $a['price'];
                    $a->button_text = 'BUY';
                
                $all_variants[] = $a;
                }
    

  2. You can use next trick for this

    $all_variants = $p->variants;
    foreach ($all_variants as &$a) {
        $tmp = (array)$a;
        $tmp['discount_price'] = $tmp['price'];
        $tmp['original_price'] = $tmp['price'];
        $tmp['button_text'] = 'BUY';
        $a = (object)$tmp;
    }
    

    Here object converted to array modified and converted to object again

    php code online test

    Login or Signup to reply.
  3. You can modify the original array, but not the copy of the element you get in the loop…

    foreach($p->variants as $i => $a) {
        // $p->variants[ $i ] corresponds to $a
        $p->variants[ $i ]['discount_price'] = $a['price'];
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search