使用foreach循环查找变量POST数据

时间:2012-09-18 15:46:24

标签: php variables post foreach

为什么这不起作用?

// I'm sending this data: $_POST['amount_1'] = '3';
$val = '1'; // This is coming from a foreach loop, but I'm specifying here for simplicity
echo $_POST['amount_'.$val]; // Returns null
echo $_POST['amount_1']; // Returns 3

尝试获取POST值时是否不允许变量?

修改:每个请求发布更多代码。

$outgoing = array();

foreach($_POST as $key => $val):
    if(strpos($key,'_number_')){ // Matching 'item_number_' would return false because of 0-indexing
        $item_id = $val;
        $test = str_replace('item_number_',$key); // Realized when pasting this that I didn't have a $replacement defined.
        $quantity = $_POST['quantity_'.$test];

        $name = $_POST['lp-name'];
        $email = $_POST['lp-email'];
        $phone = $_POST['lp-phone'];

    array_push($outgoing,array($test,$item_id,$quantity,$name,$email,$phone));
    }
endforeach;

$json = json_encode($outgoing);

立即行动。我的str_replace()中没有定义$replacement

1 个答案:

答案 0 :(得分:0)

您可以在表单元素中使用数组表示法,而不是这样做:

<form>
    <input name='amount[]' value='this is first'>
    <input name='amount[]' value='this is second'>
    <input name='amount[]' value='this is last'>
</form>

提交此表单将以数组格式发送数据:

echo $amount[0]; // this is first
echo $amount[1]; // this is second
echo $amount[2]; // this is last

祝福,

Korvin