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

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

问题描述:

I am having following values in an array as I did 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
 )

What I want to do is store the value [prod_sizes] => s,m,l,xl,xxl,xxxl,41,42,43,44,45 which is in the array into a new array variable using foreach loop, so it looks like

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

How to achieve it I am using the following code:

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

But i am getting output something like this which was not expected.

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
)

In above values it's only showing the 1st values encountered in each variable.

Anyone can help me with this logic,

Thanks in advance

我在数组中有以下值: print_r($ _ POST); code> p>

 数组
(
 [prod_category] ​​=> 2 
 [prod_for] => 2 
 [prod_brand] => 1 
 [prod_name]  =>这是一个产品
 [prod_price] => 100 
 [prod_discount] => 102 
 [prod_sizes] => s,m,l,xl,xxl,xxxl,41,42,43  ,44,45 
 [prod_colors] =>橙色,白色,红色,蓝色
 [prod_description] =>这是一个演示产品描述
 [prod_stock] => 100 
)
  code  >  pre> 
 
 

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

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

如何实现它我使用以下代码: p> $ sizes = $ temp = array(); foreach($ _POST as $ key => $ _POST [“prod_sizes”]) { $ temp = explode(',',$ _ POST) [“prod_sizes”]); $ sizes [] = $ temp [0]; } print_r($ sizes); code> pre>

但我是 得到这样的输出是不合预期的。 p>

  Array 
(
 [0] => 2 
 [1] => 2 
 [2  ] => 1 
 [3] =>这是一个产品
 [4] => 100 
 [5] => 102 
 [6] => s 
 [7] =  > orange 
 [8] =>这是一个演示产品描述
 [9] => 100 
)
  code>  pre> 
 
 

在上面的值中它是 ONL y显示每个变量中遇到的第一个值。 p>

任何人都可以帮助我理解这个逻辑, p>

提前致谢 p>

You do not need any loop here.

Just do:

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