【问题标题】:PHP $_POST data into VariablePHP $_POST 数据到变量
【发布时间】:2015-01-07 11:49:59
【问题描述】:

我有来自表单字段集的以下 $_POST 数据

array(2) { 
   ["item-1"] => 
       array(2) { 
           ["name"]=> string(5) "apple" 
           ["price"]=> string(1) "5" 
       } 
   ["item-2"] => 
       array(2) { 
           ["name"]=> string(6) "orange" 
           ["price"]=> string(1) "2" 
       }
} 

我想使用 foreach 将此帖子数据存储到变量中,例如 $name_1 $price_1 & $name_2 $price_2

如何解析这个表单数据?

【问题讨论】:

  • 这似乎是一个非常糟糕的主意,因为您可能有未知数量的条目。你的用例到底是什么?为什么要$name_1$name_2等变量?
  • 使用数组而不是像这样使用变量。

标签: php arrays json parsing


【解决方案1】:

尽管我认为以这种方式使用变量完全不合逻辑,但这可以帮助您。 它使用给定的信息自动创建变量..

//array with values
$source = [
    'item-1' => [
        'name' => 'apple',
        'price' => '5',
    ],
    'item-2' => [
        'name' => 'orange',
        'price' => '2'
    ]
];

foreach($source as $k=>$array) {
    //get all integer values from the key
    $int = preg_replace('/[^0-9]/', '', $k);

    //foreach property in $array, create the variable name + the integer number 
    //as a variable and set the value belonging to the key
    foreach($array as $name=>$value) {
        ${$name . '_' . $int} = $value;
    }
}

【讨论】:

  • 其实这是最能反映问题的答案。
【解决方案2】:
$i = 1;
foreach($_POST as $data) {
    ${'name_' . $i}  = $data["name"];
    ${'price_' . $i} = $data["price"];
    $i++;
}

【讨论】:

    【解决方案3】:
    foreach ($_POST as $k => $v) {
      $i = +preg_replace('/item-(\d+)/', '$1', $k);
      foreach(array('name', 'price') as $name) {
        $key = "$name_$i";
        $$key = $v[$name];
    }
    

    希望对你有帮助。

    【讨论】:

      【解决方案4】:

      试试这个..

      <?php
      $response = 
      array(    
              'item-1' => array(
                  2 => array(
                      'name' => 'apple',
                      'price' => 5
                  ),          
              ),
              'item-2' => array(
                  2 => array(
                      'name' => 'orange',
                      'price' => 2
                  ),          
              ),
          );
      
      
      
      foreach($response as $key =>$value)
      {
      
      $k=explode("-",$key);
      $keyvalue=end($k);
      foreach($value as $result)
      {
      echo ${'name_' . $keyvalue}=$result['name'];
      echo "</br>";
      echo ${'price_' . $keyvalue}=$result['price'];
      echo "</br>";
      }
      }
      ?>
      

      【讨论】:

        猜你喜欢
        • 2012-03-30
        • 2012-09-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-21
        • 2011-07-17
        相关资源
        最近更新 更多