如何在没有foreach循环的情况下编写代码?

时间:2015-09-18 05:39:43

标签: php codeigniter

如何在没有foreach循环的情况下编写此代码?我想从数据库中获取数据,但密钥和值存储在数据库中。

<?php
$options = get_payment_mode_options();
foreach ($options as $key => $value)
{
    echo isset($form_data["personal_info"]) && $form_data["personal_info"]->payment_mode == $key ? $value : "";
}
?>

get_payment_mode_options()是辅助函数,

function get_payment_mode_options()
{
    return array(
        "o" => "Online Payment",
        "c" => "Cheque Payment"
    );
}    

2 个答案:

答案 0 :(得分:2)

检查一下,

$options = get_payment_mode_options();
$paymentmode = isset($form_data["personal_info"]) ? $form_data["personal_info"]->payment_mode : '';
echo $options[$paymentmode];

辅助功能

function get_payment_mode_options()
{
  return array(
      "o" => "Online Payment",
      "c" => "Cheque Payment"
    );
}

答案 1 :(得分:0)

<?php
function get_payment_mode_options()
{
    return array(
        "o" => "Online Payment",
        "c" => "Cheque Payment"
    );
}

// make a new function
function get_your_result($your_key)
{
    if (!$your_key) {
        return "";
    }
    $options = get_payment_mode_options();
    if(!array_key_exists($your_key,$options)){
        return "";
    }
    return $options[$your_key];
}

// dummy for test
$form_data["personal_info"] = new stdClass();
$form_data["personal_info"]->payment_mode = "o";
$k = $form_data["personal_info"]->payment_mode;
// ~dummy for test

// echo result
echo "----".PHP_EOL;
echo get_your_result($k).PHP_EOL;
echo "----".PHP_EOL;