1

When saving in an array the prices and ids of a product, with this code...

foreach($resource->group->tabs as $tab) {

                foreach($tab->articles as $article) 
                {
                    $prices_and_ids[] = array(
                        $article->article_erp_id => array(
                            'price_pvp'       => $article->price_pvp,
                            'price_promotion' => $article->price_promotion,
                        )
                    ); 
                }
            }

The result of $prices_and_ids with this code is an object with the keys numbered:

array:10 [▼
  0 => array:1 [▼
    3140 => array:2 [▼
      "price_pvp" => 6.5
      "price_promotion" => 5.53
    ]
  ]
  1 => array:1 [▼
    3141 => array:2 [▼
      "price_pvp" => 7.5
      "price_promotion" => 6.37
    ]
  ]
  2 ... ... ...

The result I want is that the article ids are the keys of the array.

I want this:

array:10 [▼
  3140 => array:1 [▼
      "price_pvp" => 6.5
      "price_promotion" => 5.53
  ]
  3141 => array:1 [▼
      "price_pvp" => 7.5
      "price_promotion" => 6.37
  ] ... ... ...
2
  • 3
    try this $prices_and_ids[$article->article_erp_id] = array( 'price_pvp' => $article->price_pvp, 'price_promotion' => $article->price_promotion, ); Commented May 23, 2019 at 9:59
  • do you want it as a answer Commented May 23, 2019 at 10:00

3 Answers 3

3

the problem with your code is your adding it in another array do this

$prices_and_ids[$article->article_erp_id]

instead of

$prices_and_ids[]

foreach($resource->group->tabs as $tab) {
 foreach($tab->articles as $article) 
        {
            $prices_and_ids[$article->article_erp_id] = array(
                $article->article_erp_id => array(
                    'price_pvp'       => $article->price_pvp,
                    'price_promotion' => $article->price_promotion,
                )
            ); 
        }
    }
Sign up to request clarification or add additional context in comments.

Comments

0

Instead of $prices_and_ids[] you should use $prices_and_ids[$article->article_erp_id]

foreach($resource->group->tabs as $tab) {

        foreach($tab->articles as $article) 
        {
            $prices_and_ids[$article->article_erp_id] array(
                    'price_pvp'       => $article->price_pvp,
                    'price_promotion' => $article->price_promotion,
                );

        }
    }

Comments

0

Change your foreach body as following code

$prices_and_ids[$article->article_erp_id] = array(
    'price_pvp'       => $article->price_pvp,
    'price_promotion' => $article->price_promotion,
);

Comments

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.