I am trying to sort multidimensional arrays by a single column. I have an array that is created in a method and returned as $GDdata. This is a snippet of my unsorted array displayed in a table.
Here I am selecting the column I want the final array to be sorted by:
$GDcol = array_column($GDdata,0);
I can successfully print the selected column to the screen as seen here.
Then when I try to use the selected column to sort the entire multidimensional array like this:
$GDsorted = array_multisort($GDcol,SORT_ASC,$GDdata);
, my table that is printing out the array no longer shows up when I use my sorted array $GDsorted. This worked for me when I was using php 5.6. Now I have updated to php 7.2 (which is why the array_column is created first). I have tried taking out the SORT_ASC since it is default and I have tried combining the array_column and array_multisort into a one liner as I had it in php 5.6. I can not figure out why the array will not display after using array_multisort. I have seen posts that suggest using usort, however array_multisort is what I want to use if possible. If anyone needs more info please let me know. I appreciate your help.
Advertisement
Answer
From array_multisort:
array_multisort ( array &$array1 , mixed $array1_sort_order = SORT_ASC , mixed $array1_sort_flags = SORT_REGULAR , mixed ...$rest ) : bool
Returns true on success or false on failure.
&$array1
means that it (and the other arrays) are passed by reference and are sorted in place. So use that not the return:
array_multisort($GDcol, SORT_ASC, $GDdata); print_r($GDdata);
And you can do it in one line and don’t need SORT_ASC
:
array_multisort(array_column($GDdata, 0), $GDdata);
Both will sort $GDcol
and then sort $GDdata
in the same order.