PHP $_POST 数据到变量
PHP $_POST data into Variable
我有来自表单字段集的以下 $_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 将此 post 数据存储到变量中,例如 $name_1
$price_1
& $name_2
$price_2
如何解析此表单数据?
$i = 1;
foreach($_POST as $data) {
${'name_' . $i} = $data["name"];
${'price_' . $i} = $data["price"];
$i++;
}
foreach ($_POST as $k => $v) {
$i = +preg_replace('/item-(\d+)/', '', $k);
foreach(array('name', 'price') as $name) {
$key = "$name_$i";
$$key = $v[$name];
}
希望对您有所帮助。
虽然我认为这样使用变量是完全不合逻辑的,但这可以帮助你。
它使用给定的信息自动创建变量..
//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;
}
}
试试这个..
<?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>";
}
}
?>
我有来自表单字段集的以下 $_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 将此 post 数据存储到变量中,例如 $name_1
$price_1
& $name_2
$price_2
如何解析此表单数据?
$i = 1;
foreach($_POST as $data) {
${'name_' . $i} = $data["name"];
${'price_' . $i} = $data["price"];
$i++;
}
foreach ($_POST as $k => $v) {
$i = +preg_replace('/item-(\d+)/', '', $k);
foreach(array('name', 'price') as $name) {
$key = "$name_$i";
$$key = $v[$name];
}
希望对您有所帮助。
虽然我认为这样使用变量是完全不合逻辑的,但这可以帮助你。 它使用给定的信息自动创建变量..
//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;
}
}
试试这个..
<?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>";
}
}
?>