0

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.

3
  • 1
    Welcome to Stack Overflow! Please post a minimal reproducible example. Commented Apr 13, 2021 at 19:29
  • 1
    And post plain text, not screenshots. Commented Apr 13, 2021 at 19:30
  • Sorry @Barmar I'll remember those notes for next time, thank you. Commented Apr 13, 2021 at 20:15

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you this worked! It did not click in my head that it returns a boolean instead of the sorted array. Also I read somewhere that doing it on one line would throw a warning saying "variables can only be passed by reference" but that did not pop up for me. Thank you for your time!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.