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 :)
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'];
}
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");
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 . "
";
}