基于POST变量循环遍历数组 - PHP

时间:2017-04-10 15:06:52

标签: php arrays post

我目前有一个接收表单数据的页面,我有两条帖子信息 -

$country_name = $_POST[“country_name”];
$price_point = $_POST[“price_point”];

我目前有一个电子表格,其中包含

列中的此信息

Information Format

我需要能够运行一个使用post变量的函数,并从数组中找到相应的值。

我还没有创建一个数组,因为我不知道格式化这个数组的最佳方法。这是我在努力的地方..

示例输出将是;

国家的后期价值是美国。 价格点是2。 该值为1.5。

对任何可以帮助我解决以下问题的人的热爱!

由于

2 个答案:

答案 0 :(得分:1)

我会像这样创建一个数组

$dataPoints = array(
    array(
        'point' => 1,
        'price' => 1.5,
        'country' => 'UK'
    ),
    array(
        'point' => 1,
        'price' => 1.3,
        'country' => 'US'
    ),
    array(
        'point' => 1,
        'price' => .8,
        'country' => 'SWEDEN'
    ),
    ...
)

这样的功能
function getPrice($pricePoint, $country) {
    // Search in array for good price
    foreach ($dataPoints as $dataPoint) {
        if ($dataPoint['point'] == $pricePoint && $dataPoint['country'] == $country) {
            return $dataPoint['price'];
        }
    }
    return null;
}

并使用您的帖子参数进行调用

$pp = filter_input(INPUT_POST, 'price_point');
$country = filter_input(INPUT_POST, 'country_name');
$price = getPrice($pp,$country);

echo 'Country is ', $country, '. The price point is ', $pp, '. The price is ', $price;

答案 1 :(得分:0)

或者我只是将值放在多维数组中,如下面的例子

一旦这个电子表格变得更大,我建议从数据库中的值生成数组。

<?php
    $country_name = 'UK';
    $price_point = 4;

    $arr = array(
        'UK' => array(
            1 => 1.5,
            2 => 1.6,
            3 => 1.9,
            4 => 12
        ),
        'US' => array(
            1 => 1.3,
            2 => 1.5,
            3 => 1.6,
            4 => 1.7
        ),
        'SWEDEN' => array(
            1 => 0.8,
            2 => 0.7,
            3 => 0.5,
            4 => 0.3
        )
    );

    $value = $arr[$country_name][$price_point];
    echo $value;
    // echoes 12
?>