使用foreach循环PHP

时间:2019-05-23 09:57:35

标签: php laravel laravel-5

使用此代码在数组中保存产品的价格和ID时...

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,
                        )
                    ); 
                }
            }

使用此代码的 $ prices_and_ids 的结果是对象的键编号为:

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

我想要的结果是商品ID是数组的键。

我想要这个:

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

3 个答案:

答案 0 :(得分:3)

您的代码的问题是您将其添加到另一个数组中

  

$ prices_and_ids [$ article-> article_erp_id]

代替

  

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

答案 1 :(得分:0)

而不是$ prices_and_ids [],您应该使用$ 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,
                );

        }
    }

答案 2 :(得分:0)

按照以下代码更改您的foreach正文

N=10000;
a = randn(N,1);
order = 60;
for i=order:length(a)
    data(i-order+1,:) = a([i:-1:i-order+1])';
end