如何使用PHP中的foreach循环将特定值存储到$ _POST数组内的另一个数组中

时间:2017-04-18 11:47:59

标签: php foreach

我在数组中有以下值print_r($_POST);

Array
 (
   [prod_category] => 2
   [prod_for] => 2
   [prod_brand] => 1
   [prod_name] => this is a product
   [prod_price] => 100
   [prod_discount] => 102
   [prod_sizes] => s,m,l,xl,xxl,xxxl,41,42,43,44,45
   [prod_colors] => orange,white,red,blue
   [prod_description] => this is a demo product descrption
   [prod_stock] => 100
 )

我想要做的是使用foreach循环将数组中的值[prod_sizes] => s,m,l,xl,xxl,xxxl,41,42,43,44,45存储到一个新的数组变量中,所以它看起来像

Array
 (
   [0] => s
   [1] => m
   [2] => l
   [3] => xl
   [4] => xxl
   [5] => xxxl
   [6] => 41
   [7] => 42
   [8] => 43
   [9] => 44
   [9] => 45
 )

如何实现它我使用以下代码:

$sizes = $temp = array();
foreach ($_POST as $key => $_POST["prod_sizes"])
    {
        $temp = explode(',', $_POST["prod_sizes"]);
        $sizes[] =  $temp[0];
    }
print_r($sizes);

但我得到的输出类似于预期的输出。

Array
(
  [0] => 2
  [1] => 2
  [2] => 1
  [3] => this is a product
  [4] => 100
  [5] => 102
  [6] => s
  [7] => orange
  [8] => this is a demo product descrption
  [9] => 100
)

在上面的值中,它只显示每个变量中遇到的第一个值。

任何人都可以帮助我解决这个问题,

提前致谢

1 个答案:

答案 0 :(得分:4)

这里不需要任何循环。

只是做:

$sizes = explode(',', $_POST["prod_sizes"]);