duanjue9296
2017-04-18 11:47
浏览 53
已采纳

如何使用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

图片转代码服务由CSDN问答提供 功能建议

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

 数组
(
 [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 
)
   
 
 

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

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

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

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

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

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

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

提前致谢 < / DIV>

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douweicheng5532 2017-04-18 11:49
    已采纳

    You do not need any loop here.

    Just do:

    $sizes = explode(',', $_POST["prod_sizes"]);
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报