Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to sort array like mysql

Tags:

arrays

php

mysql

how to sort array which is the same with datebase data?

I requested google analytics datas, the datas is an larget array , I want to join the array with some other fields from my local database , then I extend the large array again. Now I want to sort the large array which is the same with using my sql like this:

select * from ga_table where ...
select * from ga_table order by age
select * from ga_table group by name

my array now is like:

$arr=array(
    'header'=>array('name','age','money'),
    'values'=>array(
        array('jimmy',20,30),
        array('tina',18,12),
        array('darcy',19,50),
    )
);

but now I had a large array not a db table , then how to sort the array ? enter image description here

like image 208
mingfish_004 Avatar asked Jan 13 '23 01:01

mingfish_004


2 Answers

you can try array_multisort: http://php.net/manual/en/function.array-multisort.php

foreach ($arr['values'] as $key => $row) {
    $name[$key]  = $row[0];
    $age[$key] = $row[1];
    $money[$key] = $row[3];
}

now if you want to sort by name in ASC you can:

array_multisort($name, SORT_ASC, $arr['values']);

or by name DESC:

array_multisort($name, SORT_DESC, $arr['values']);

or age ASC:

array_multisort($age, SORT_ASC, $arr['values']);

or age DESC and name ASC

array_multisort($age, SORT_DESC, $name, SORT_ASC, $arr['values']);
like image 80
mamdouh alramadan Avatar answered Jan 17 '23 12:01

mamdouh alramadan


 asort(); 
 arsort();
 krsort(); 

etc.. all are PHP inbuilt functions used to sort the array.

For better understanding you can visi the link http://php.net/manual/en/array.sorting.php

like image 32
Krish R Avatar answered Jan 17 '23 12:01

Krish R