Home > OS >  Sort the currency values using php
Sort the currency values using php

Time:08-22

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?

CodePudding user response:

You can try this:

$collection = collect([
        ['price' => '$13.00'],
        ['price' => '$12.00'],
        ['price' => '$15.00'],
]);
     
$sorted = $collection->sortBy('price');
dd($sorted);

CodePudding user response:

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

CodePudding user response:

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.

CodePudding user response:

Since this is Laravel you can use collection methods such as sortBy.

$rates = DB::table('rates')->all()->sortBy('name', SORT_NATURAL);

SORT_NATURAL is a flag to use the "natural sort" of items (which is to sort by length and then alphabetically so e.g. $100 will come after $10)

  • Related