douqinlu4217 2013-07-17 03:44
浏览 25

排序结果mysql / php

Lets say i have a list full of phones. It's easy to print all the phones out in a unordered list like:

$get_phones = $mysqli->query("
SELECT
    a.id,
    b.phone_id,
    a.phonename AS pname,
    b.modelname AS mname,
FROM phone_brands 
a LEFT OUTER JOIN phone_models b
ON a.id = b.phone_id");

while($phones = $get_phones->fetch_assoc()){
echo $phones['pname'] . $phones['mname'];}

But how can i make the list more readable by sorting all the models and phones like:

Iphone
3G
3GS
4G

Nokia
Lumia 1020
Lumia 925
Lumia 520

My guess is that i should do something like:

if($phones['pname'] == $phones['pname']{}

But i don't know if i'm far away here? Any help would be appreciated :)

  • 写回答

3条回答 默认 最新

  • douye8500 2013-07-17 03:52
    关注

    Well ofcourse you could order the query by mname:

    $get_phones = $mysqli->query("
    SELECT
        a.id,
        b.phone_id,
        a.phonename AS pname,
        b.modelname AS mname,
    FROM phone_brands 
    a LEFT OUTER JOIN phone_models b
    ON a.id = b.phone_id
    ORDER BY mname");
    

    And then in php do something like:

    $currentModel = "";
    
    while($phones = $get_phones->fetch_assoc()){
        if($currentModel != $phones['mname']){
            echo $phones['mname'].'<br/>';
            $currentModel = $phones['mname'];
        }
        echo $phones['pname'];
    }
    
    评论
  • doucheng3407 2013-07-17 03:56
    关注

    Sorting on the database level is much faster and at the end, the result is the same. You can just read it in a PHP array and have it sorted.

    $get_phones = $mysqli->query("
    SELECT
        a.id,
        b.phone_id,
        a.phonename AS pname,
        b.modelname AS mname,
    FROM phone_brands 
    a LEFT OUTER JOIN phone_models b
    ON a.id = b.phone_id
    order by pname, mname");
    
    评论
  • dscbxou1900343 2013-07-17 03:59
    关注
    SELECT
        a.id,
        b.phone_id,
        a.phonename AS pname,
        b.modelname AS mname,
    FROM phone_brands AS a 
    LEFT OUTER JOIN phone_models AS b
        ON a.id = b.phone_id
    ORDER BY pname, mname DESC
    

    That should do the job from what your question asks?

    [edit]

    I need to improve the code, i'm thinking using something like a foreach so it's more useable later than just order by :P – Simon Duun

    Going on that comment, you could still use the order by in the query but do something like:

    $phone_array = array();
    while($phones = $get_phones->fetch_assoc()){
        $phone_array[$phones['pname']] =  $phones['pname'] . $phones['mname'];
    }
    
    ksort($phone_array);
    
    foreach($phone_array as $phone_pname => $phone_value){
        echo $phone_pname . ' -> ' . $phone_value . "
    ";
    }
    
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部