Jump to content

MYSQl Data not displaying numbers in order


Go to solution Solved by Barand,

Recommended Posts

Hello,

 

I have the following code to get data from mysql.

SELECT COUNT(*),pickup FROM journeys WHERE pickup_type='postcode' GROUP BY pickup HAVING COUNT(*)>=1

The result is like this;

 

E1

E10

E11

E12

E13

E2

E3

E4

.......

 

 

I need to display the data starting from E1 ...... to ....E13 (or whatever the last entry is).

 

Could anyone help?

 

Regards

you could store the results in an array then use natsort

$arr = array (
    'E1',
    'E10',
    'E11',
    'E12',
    'E13',
    'E2',
    'E3',
    'E4'
);
natsort($arr);

echo '<pre>',print_r($arr, true),'</pre>';

/* OUTPUT *************************
Array
(
    [0] => E1
    [5] => E2
    [6] => E3
    [7] => E4
    [1] => E10
    [2] => E11
    [3] => E12
    [4] => E13
)
**************************************/

So can I do this with mysql too.

 

Can the following code output the same result?

($pickup is populated from database)

$pickup= array ($pickup);
natsort($pickup);

echo '<pre>',print_r($pickup, true),'</pre>';
  • Solution

Sorry, forget the natsort. If you store the results of the query in an array then you will need a custom sort function using strnatcmp

 

EG

$sql = "SELECT COUNT(*) as ct, pickup 
        FROM journeys 
        WHERE pickup_type='postcode' 
        GROUP BY pickup 
        HAVING COUNT(*)>=1";
$res = $mysqli->query($sql);
while ($row = $res->fetch_assoc()) {
    $data[] = $row;
}


usort($data, function($a,$b){
        return strnatcmp($a['pickup'], $b['pickup']);
        });

echo '<pre>';
foreach ($data as $row) {
    printf ('%-4s %d<br>',  $row['pickup'], $row['ct']);
}
echo '</pre>';

/* OUTPUT EXAMPLE************************

E1   4
E2   2
E10  3
E11  1

**************************************/
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.