如何在查询结果

时间:2015-07-17 02:26:54

标签: php sql mysqli

我有一个函数,我根据mysqli查询构建一个数组:

if ($type == 'item') {

    $the_query = "SELECT ID, SKU from store_items WHERE Qty > 0";

} else if ($type == 'brim') {

    $the_query = "SELECT ID, BrimID from store_item_brims";

} else if ($type == 'condition') {

    $the_query = "SELECT ID, CondDesc from store_item_conditions";

} else if ($type == 'grade') {

    $the_query = "SELECT ID, GradeDesc from store_item_grades";

}

$query = $db->query($the_query);

    if ($query->num_rows > 0) { 

        $results = array();

        while ($returned = $query->fetch_assoc()) {

            array_push($results, $returned);

        }
    }

    return $results;

例如,如果$typeitem,我会有一个类似的数组:

$array['ID'] // Some ID
$array['SKU'] // The SKU

如果$typebrim,我会:

$array['ID'] // Some ID
$array['BrimID] // A brim ID

我要做的是修改查询,这样无论如何,生成的数组都会有相同的键,即:

$array['ID']
$array['Value']

因此,无论$type是什么,数组始终都有IDValue的键。

如何修改这些查询才能执行此操作?

1 个答案:

答案 0 :(得分:4)

只使用一个别名(最好是一个有意义的别名,而不是我使用的whatever):

if ($type == 'item') {    
    $the_query = "SELECT ID, SKU as whatever from store_items WHERE Qty > 0";    
} else if ($type == 'brim') {    
    $the_query = "SELECT ID, BrimID as whatever from store_item_brims";    
} else if ($type == 'condition') {    
    $the_query = "SELECT ID, CondDesc as whatever from store_item_conditions";    
} else if ($type == 'grade') {    
    $the_query = "SELECT ID, GradeDesc as whatever from store_item_grades";    
}

PHP:

$array['ID']
$array['whatever']