PHP $ _POST数据变为Variable

时间:2015-01-07 11:50:00

标签: php arrays json parsing

我在表单字段集

中跟踪了$ _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

如何解析此表单数据?

4 个答案:

答案 0 :(得分:2)

虽然我认为以这种方式使用变量是完全不合逻辑的,但这可以帮到你。 它使用给定的信息自动创建变量..

//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;
    }
}

答案 1 :(得分:0)

$i = 1;
foreach($_POST as $data) {
    ${'name_' . $i}  = $data["name"];
    ${'price_' . $i} = $data["price"];
    $i++;
}

答案 2 :(得分:0)

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

希望它有所帮助。

答案 3 :(得分:0)

试试这个..

<?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>";
}
}
?>
相关问题