if语句在while循环中

时间:2013-10-06 00:50:58

标签: javascript php mysql

我有一个PHP脚本,可以从MySQL数据库中的表中获取一些数据。 然后它使用JSON javascript将此信息发送回PHP页面。

一切都很好但我想在while循环中创建一个if语句。 我的“used”表发回“1”和“5”而不是回显1或5我希望它发送是或否。

执行此操作的一种方法是分解$ data并将1或5替换为Yes或No. 但还有其他方法吗?

Something like: `if (used == '1') { set used == 'No } else {set used == 'Yes' }`

我的代码

 while ($row = $result->fetch_assoc()) {
    $data['results'][] = array(
        'id' => $row['id'],
        'number' => $row['number'],
        'type' => $row['type'],
        'code' => $row['code'],
        'price' => $row['price'],
        'used' => $row['used'],
        'utime' => $row['utime'],
        'username' => $row['username']
    );
}
//Everything went to plan so set success to true
$data['success'] = true;

//Set the content type for a json object and ensure charset is UTF-8. NOt utf8 otherwise it will not work in IE (Darn IE! >.<)
header("Content-Type: application/json; charset=UTF-8");

//json encode the data and cast to an object so we can reference items like this.id in the javascript instead of this['id'] etc.
echo json_encode((object)$data);

2 个答案:

答案 0 :(得分:3)

您可以在数组赋值中使用条件运算符:

'used' => $row['used'] == 1 ? 'Yes' : 'No',

答案 1 :(得分:0)

您可以在没有if声明的情况下执行此操作:

$answer = array(0 => 'No', 1 => 'Yes');

...
'used' => $answer[ $row['used'] ],
...
相关问题