我有这段代码:
$string = "prItem1,prItem2,prItem3"; // could contains more
$itemarray = explode(',', $string);
foreach($itemarray as $var)
{
//echo $var."<br/>";
// HERE I want "convert" any found prItem ($var) to a handle
// that give me something like that:
// $prItem1 = $_POST['prItem1'];
// $prItem2 = $_POST['prItem2'];
// ...
}
当我在代码注释中写道:每个prItem都是一个输入字段,我想得到$ _POST-Vars。
有人知道我怎么能这样做吗?或者,如果有更好的方法来实现这个目标吗?
答案 0 :(得分:1)
您可能希望尝试基于对象的方法,如下所示:
<?php
$string = "prItem1,prItem2,prItem3"; // could contains more
$itemArray = explode(',', $string);
// INSTANTIATE A NEW NATIVE PHP OBJECT TO HOLD YOUR DATA...
$objItems = new stdClass();
// LOOP THROUGH THE $itemArray:
foreach($itemArray as $var){
// CREATE INDIVIDUAL KEYS MATCHING UP TO THE DESIRED KEYS AS IN: prItem1, prItem2, etc...
$key = $var;
// ASSIGN THE KEY TO THE OBJECT WHILE SETTING THE VALUE OF THIS OBJECT KEY TO THE POST VALUE...
$objItems->$key = $_POST[$var];
// ... MORE LOGIC FOLLOWS...
}
// ACCESS YOUR ITEMS LIKE SO...
//$objItems->prItem1
var_dump($objItems->prItem1);
这是另一个变体;这次使用数组代替:
<?php
$string = "prItem1,prItem2,prItem3"; // could contains more
$itemArray = explode(',', $string);
// INSTANTIATE A NEW ARRAY TO HOLD YOUR DATA...
$arrItems = array();
// LOOP THROUGH THE $itemArray:
foreach($itemArray as $var){
// CREATE INDIVIDUAL KEYS MATCHING UP TO THE DESIRED KEYS AS IN: prItem1, prItem2, etc...
$key = $var;
// ASSIGN THE KEY TO THE ARRAY WHILE SETTING THE VALUE OF THIS KEY TO THE POST VALUE...
$arrItems[$key] = $_POST[$var];
// ... MORE LOGIC FOLLOWS...
}
// EXTRACT EACH INDIVIDUAL ARRAY DATA INTO AN OWN VARIABLE
extract($arrItems);
// ACCESS YOUR VARIABLES DIRECTLY
// LIKE YOU WOULD A PREVIOUSLY DEFINED VARIABLE LIKE SO...
var_dump($prItem1);
编辑:模拟任意后评价 - 仅用于测试目的。
<?php
$POST = array("prItem1"=>"Value of prItem1", "prItem2"=>"Value of prItem2", "prItem3"=>"Value of prItem3");
$string = "prItem1,prItem2,prItem3"; // could contains more
$itemArray = explode(',', $string);
// INSTANTIATE A NEW ARRAY TO HOLD YOUR DATA...
$arrItems = array();
// LOOP THROUGH THE $itemArray:
foreach($itemArray as $var){
// CREATE INDIVIDUAL KEYS MATCHING UP TO THE DESIRED KEYS AS IN: prItem1, prItem2, etc...
$key = $var;
// ASSIGN THE KEY TO THE ARRAY WHILE SETTING THE VALUE OF THIS KEY TO THE POST VALUE...
$arrItems[$key] = $POST[$var];
// ... MORE LOGIC FOLLOWS...
}
// EXTRACT EACH INDIVIDUAL ARRAY DATA INTO AN OWN VARIABLE
extract($arrItems);
// ACCESS YOUR VARIABLES DIRECTLY
// LIKE YOU WOULD A PREVIOUSLY DEFINED VARIABLE LIKE SO...
var_dump($prItem1);
var_dump($prItem2);
var_dump($prItem3);
我希望这能帮到你......
答案 1 :(得分:1)
$string = "prItem1,prItem2,prItem3"; // could contains more
$itemarray = explode(',', $string);
$posts = array();
//remove empty elements from $itemarray
foreach(array_filter($itemarray) as $var)
{
if(isset($_POST[$var])) {
$posts[$var] = $_POST[$var];
}
}
print_r($posts);