Domanda

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']);
È stato utile?

Soluzione

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);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top