1

let say I have one array ($results) containing arrays (location, start_date, coord_lng, coord_lat etc...). The idea is that I would like to sort $result by start_date which is pretty simple using array_multisort. Where it is becoming more difficult is that all other arrays (location, coord_lng, coord_lat etc) should be reorganized the same way and I don't know how to do it !

looking at solution provided here: PHP: Sort multi-dimension array I am not sure how to adapt to more than 2 arrays...

I have produced this code but is there anything quicker ?

foreach ($row['table'] as $key2 => $row2) 
{
    if($key2 != 'debut')
    {
        $dates =  $results[$key]['table']['debut'];
        array_multisort($dates, SORT_ASC, $results[$key]['table'][$key2]);
    }
 }
 $dates =  $results[$key]['table']['debut'];
 array_multisort($dates, SORT_ASC, $results[$key]['table']['debut']);
2
  • 1
    You don't show any example data and what it should be after sort. Commented Dec 9, 2013 at 22:01
  • You could probably use a bit less memory if you pass $row2 by reference (by using & in the loop iteration, like $key2 => &$row2). Then you can manipulate $row2 directly instead of calling $results[$key]['table'][$key2]. That being said, I don't think the savings will be particularly huge, though your code will be a little easier to understand. Commented Dec 9, 2013 at 22:10

1 Answer 1

0

Do you need the values to be distributed in different arrays? I prefer information that belongs together to be grouped in code as well. This makes it easy to extract one point (and all of its information), add new points as well as sorting.

In this example it means $results would look like this

[
    location1,
    start_date1,
    etc...
],
[
    location2,
    start_date2,
    etc...
],
[
    location3,
    start_date3,
    etc...
]

Now you can sort them via usort() and have values that belong together still grouped together.


I've created a small example (watch it work here)

$arr1 = array("foo", "ybar", "baz");
$arr2 = array("foo2", "ybar2", "baz2");
$arr3 = array("foo3", "ybar3", "baz3");

$results = array();
foreach ($arr1 as $key=>$value) {
    $results[] = array(
        'arr1' => $value,
        'arr2' => $arr2[$key],
        'arr3' => $arr3[$key],
    );
}

function sortByArr1($a, $b) {
    return strcmp($a['arr1'], $b['arr1']);
}

usort($results, "sortByArr1");

print "<pre>";
print_r($results);

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.