jeudi 23 mai 2019

Store array keys in variable with foreach loop PHP

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



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire