如果选择了来自同一组数组的不同对象的多个值,则输出数组对象值

时间:2017-03-28 02:18:05

标签: php arrays ajax wordpress

我正在为一个要求3个输入的表单创建一个AJAX功能 - BEDS,BATHS,FREQUENCY。我希望输出是PRICE。因此,当用户进行输入时,它只输出我创建的数组的相应价格。

PHP CODE SNIPPET(ARRAYS):

 $pricing = array (
    array ('frequency' => "one", 'beds' => 1 , 'baths' => 1 , 'price' => 90),
    array ('frequency' => "one", 'beds' => 1 , 'baths' => 1.5 , 'price' => 113),
    array ('frequency' => "one", 'beds' => 1 , 'baths' => 2 , 'price' => 113),
    array ('frequency' => "one", 'beds' => 2 , 'baths' => 2.5 , 'price' => 135),
    array ('frequency' => "weekly", 'beds' => 3 , 'baths' => 3 , 'price' => 135),
    array ('frequency' => "weekly", 'beds' => 3 , 'baths' => 3.5 , 'price' => 158),
    array ('frequency' => "biweekly", 'beds' => 4 , 'baths' => 4 , 'price' => 158),
    array ('frequency' => "biweekly", 'beds' => 4 , 'baths' => 4.5 , 'price' => 180),
    array ('frequency' => "monthly", 'beds' => 5 , 'baths' => 5 , 'price' => 180),
    array ('frequency' => "monthly", 'beds' => 5 , 'baths' => 5.5 , 'price' => 203),
    array ('frequency' => "monthly", 'beds' => 6 , 'baths' => 6 , 'price' => 203)
);

我设法传递输入的值,但我的功能不起作用。显然我可以回显(echo $ selected_frequency_id;)从我的表单中选择的值,但我不能回显PRICE。我的功能不正确吗?我找不到foreach循环的任何问题。请参阅以下代码:

PHP代码连续性:

function ajax_update_price() {

$selected_bed_id = $_POST['bedID'];
$selected_bath_id = $_POST['bathID'];
$selected_frequency_id = $_POST['frequencyID'];

//echo $selected_frequency_id;

    foreach( $pricing as $element ) {
        if( $element['frequency'] == $selected_frequency_id && $element['beds'] == $selected_bed_id && $element['baths'] == $selected_bath_id) {
             echo $element['price'];
             break;
    }
 } 

    wp_die(); 
}

1 个答案:

答案 0 :(得分:1)

function ajax_update_price() {
  global $_POST;


$selected_bed_id = $_POST['bedID'];
$selected_bath_id = $_POST['bathID'];
$selected_frequency_id = $_POST['frequencyID'];


foreach( $pricing as $element ) {
    if( ($element['frequency'] == $selected_frequency_id) && ($element['beds'] == $selected_bed_id) && ($element['baths'] == $selected_bath_id)) {
         echo $element['price'];
         break;
   }
  } 

wp_die(); 
}

但我有更漂亮的解决方案:

 $pricing["one"]["1"]["1"] = 90;
 $pricing["one"]["1"]["1.5"] = 113;
 $pricing["one"]["1"]["2"] = 113;
 $pricing["one"]["2"]["2.5"] = 135;
 $pricing["one"]["2"]["2.5"] = 135;
 $pricing["weekly"]["3"]["3"] = 135;
 $pricing["weekly"]["3"]["3.5"] = 158;
// and so on, i think you understand how to continue

并且新功能将是:

function ajax_update_price() {
  global $_POST;


$selected_bed_id = $_POST['bedID'];
$selected_bath_id = $_POST['bathID'];
$selected_frequency_id = $_POST['frequencyID'];

if ($pricing[$selected_frequency_id][$selected_bed_id][$selected_bath_id])
    print $pricing[$selected_frequency_id][$selected_bed_id][$selected_bath_id]

  wp_die(); 
}