1

I'm trying to sort following array:

$myArray = array(
    "ID"    =>  array(
                    0,
                    5,
                    8,
                    12,
                    15
                ),
    "date"  =>  array(
                    1484391600,
                    1483910300,
                    1484920000,
                    1482393630,
                    1484391600
                ),
    "name"  =>  array(
                    "Pete",
                    "Max",
                    "Tom",
                    "June",
                    "Arend"
                ),
);

I want to be able to choose which subarray is sorted and in which way (numeric / string) and order (DESC / ASC). All the other subarrays should be sorted accordingly.

Here is some code that worked at first, but when the subarray to sort contained an empty string, it failed: All subarrays where sorted differently.

$sortCatArray = $myArray['name'];

foreach($myArray as $category => $value){
    $keepOrigin = $sortCatArray;
    array_multisort($keepOrigin, SORT_DESC, SORT_STRING, $myArray[$category]);
}

var_dump($myArray);

Can someone point out what I'm doing wrong.

Also I don't want to rearrange the arrays to match the other sorting solutions as I need the values in the given format.

Community
  • 1
  • 1
  • What do you mean by *all other subarrays should be sorted accordingly*? Are you saying that the order of ID corresponds to the order of date which correspondes to the order of name? If so, I'd STRONGLY recommend reorganizing this array to be an array of *records* (instead of an array of *fields*). Then, you could sort trivially, and keep the "records" complete. Example: [['ID' => 0, 'date' => 1484391600, 'name' => 'Pete'],['ID' => 5, 'date' => 1483910300, 'name' => 'Max']]` – random_user_name Jan 20 '17 at 15:50
  • Yes that's exactly what I'm trying to do. Is it really that impractical to sort an array of fields? – user2347989 Jan 20 '17 at 16:00
  • It's not that it's impractical, it's that the relationship is too "fragile" from one to the other, and as you are learning it's *difficult* to sort them and keep the relationships in place. You wouldn't have any clear indication if the relationship was lost, whereas with the "records" approach I suggest, it's pretty clear which ID goes with which DATE and NAME. – random_user_name Jan 20 '17 at 16:03

0 Answers0