0

I have an array like this, how can I sort by "name"

Array ( 
    [0] => Array ( 
        [id] => 1 
        [name] => status_category_confide 
    ) 
    [1] => Array ( 
        [id] => 2 
        [name] => status_category_love 
    ) 
    [2] => Array ( 
        [id] => 3 
        [name] => status_category_household 
    ) 
    [3] => Array ( 
        [id] => 4 
        [name] => status_category_family 
    ) 
    [4] => Array (
        [id] => 5 
        [name] => status_category_friends 
    ) 
    [5] => Array ( 
        [id] => 6 
        [name] => status_category_colleague 
    ) 
    [6] => Array ( 
        [id] => 7 
        [name] => status_category_work 
    ) 
    [7] => Array ( 
        [id] => 8 
        [name] => status_category_ambition 
    ) 
)

I've tried using the "sort" function but it doesn't work

$get_status_mood=mysqli_query($con, "select id, name from category");
while ($gsm=mysqli_fetch_array($get_status_mood)) {
    //array_push($status_category, constant($gsm['name']));
    $status_category[] = array(
        "id"=>$gsm['id'],
        "name"=>$gsm['name']
    );
}

sort($status_category);
for ($i=0; $i<count($status_category); $i++) {
    echo"<option value='".$status_category[$i]['id']."'>".$status_category[$i]['name']."</option>";
}

I want to display the results in the order of the name

M. Eriksson
  • 13,450
  • 4
  • 29
  • 40
Adhy Musaad
  • 81
  • 1
  • 8
  • ^ That's for sorting it in PHP. But as the answer below suggests, you could (and probably should) sort it directly in the query instead. – M. Eriksson Oct 04 '18 at 05:32
  • Note to future visitors: There's no need to add more answers that's sorting it using PHP. That's all covered in the possible duplicate link above. Instead of repeating the, more or less, same answer, vote it as a duplicate instead. – M. Eriksson Oct 04 '18 at 06:17

4 Answers4

6

Try the SQL order by option

$get_status_mood=mysqli_query($con, "select id, name from category order by name asc");
VinothRaja
  • 1,405
  • 10
  • 21
1

You can sort it using array_column and array_multisort functions.

$keys = array_column($array, 'name');

array_multisort($keys, SORT_ASC, $array);
akshaypjoshi
  • 1,245
  • 1
  • 15
  • 24
0

You can try it with usort this sort an array by values using a user-defined comparison function

   function cmp($a, $b)
{
  return strcmp($a["name"], $b["name"]);
}
usort($vc_array, "cmp");
0
$a = array();
$a[] = array('id' => 1, 'name' => 'status_category_confide');
$a[] = array('id' => 2, 'name' => 'status_category_love');
$a[] = array('id' => 3, 'name' => 'status_category_household');

function cmp($x, $y) {
    if (strcmp($x['name'], $y['name']) == 0) {
        return 0;
    }
    return (strcmp($x['name'], $y['name']) < 0) ? -1 : 1;
}
usort($a, "cmp");

print_r($a);
Rubin Porwal
  • 3,736
  • 1
  • 23
  • 26