-1

MySQL Database table

Rates:

Id Name
1 $13.00
2 $20.00
3 $13.75
4 $15.00
5 $100.00

I'm trying to sort the data ASC to show on the dropdown, based on the data you can clearly understand that we can't sort the data by Id.

Here is the same code

$sorted = $rates;
foreach ($rates as $key => $data){
  if(preg_match('/[a-z]/', $data['name'])){
     unset($sorted[$key]);
     $sorted[] = $data;
   }
} 

Result:

Dropdown

Expected Result:

$13.00
$13.75
$15.00
$100.00

Can you help me to figure this out?

  • _"based on the data you can clearly understand that we can't sort the data by Id."_ - yes. But you don't understand, that you can not sort alphanumeric values, as if they were numeric ones? – CBroe Aug 22 '22 at 07:18
  • @CBroe Yes, I do. But the database structure has already been declared we can't change it. Is there a way that we can do it through our code? – K Chandrasekar Aug 22 '22 at 09:10
  • @KChandrasekar i gave u a solution without changing data structure – cile1993 Aug 26 '22 at 08:03

3 Answers3

0

Guessing ur using eloquent u can sort data when getting it from databse with orderBy

$query = Model::class('params')->orderBy('name', 'asc')->get();

Then when u do @foreach for printing it would be ID for the one with lowest price up until highest, and u dont have to deal with collections.

There is no need to delete your $ sign and change your data structure.

cile1993
  • 156
  • 10
0

You can try this:

$collection = collect([
        ['price' => '$13.00'],
        ['price' => '$12.00'],
        ['price' => '$15.00'],
]);
     
$sorted = $collection->sortBy('price');
dd($sorted);
Paul J.K
  • 603
  • 1
  • 4
  • 13
0

it's very simple instead of sorting data in php, sort data when query table

first of all delete $ in name column and save data as float and change column data type to float

now you can feel sql power

if you want to run sql query manually use this query below

select * from Rates order by Name asc

if you want to use laravel eloquent use this code below

Rate::orderBy('Name','asc')->get();

for more information about order in mysql query see this or in laravel eloquent see this