Web Hosting Geeks | Web Hosting Experts
Need help? Call us 1(866)TOP-HOST

14120 reviews 1680 hosting providers

Questions & Answers

Sorting arrays

Feb 9, 2013 by Alpha2
Hello,

I a using a multilevel array and I want to sort the array elements as:$status_array[users][user] by the respective values of the sub-items values: $status_array[users][user][n][user_name].

Does anyone have any idea how this could be done
Thank you

1 Answer

0 votes
Feb 9, 2013 by lightSpeed
If the arrays are not huge, try this php code and adjust the  array levels as you want. You would need to sort more than a key and stack them and make sure the numbers to left are padded to the max that you think they  could  be, so they sort properly . and  when building the $index, add a ~# at the end so that your keys are  unique.
PHP Code:
<?php

$data = array(
    array('name'=>'A','location'=>'A1','age'=>30),
    array('name'=>'B','location'=>'B1','age'=>25),
    array('name'=>'C','location'=>'C1','age'=>30),
);

// single value sorting and displaying (BY age)

$order = array();$n=0;
foreach($data as $key=>$user) {
        $index = $user['age'].'~'.$n++;
    $order[$index] = $key;
}
ksort($order);

foreach($order as $key) {
    echo implode(', ',$data[$key]),"<br>\n";
}

echo "<hr>";

// double value sorting and displaying (by name and age)
$order = array();$n=0;
foreach($data as $key=>$user) {
    
    $index = str_pad($user['name'],3,'0',STR_PAD_LEFT).'~'.$user['age'].'~'.$n++;
    $order[$index] = $key;
}
ksort($order);


foreach($order as $key) {
    echo implode(', ',$data[$key]),"<br>\n";
}

?>