Search code examples
phparrayssortingmultidimensional-arrayzend-framework

Sorting a multidimensional array when the numbers are strings in PHP


I'm creating a ticket system in Zend Framework and I need to sort the tickets by status, only problem is that the status is a string.

This is what one entry in my array looks like:

`[1] => array(14) {
    ["ticket_id"] => string(3) "147"
    ["created_at"] => string(19) "2017-02-23 14:21:55"
    ["updated_at"] => string(19) "0000-00-00 00:00:00"
    ["deadline"] => string(19) "0000-00-00 00:00:00"
    ["scheduled_for"] => string(19) "0000-00-00 00:00:00"
    ["priority"] => string(1) "1"
    ["tracker"] => string(1) "1"
    ["status"] => string(1) "3"
    ["author"] => string(1) "12"
    ["assigned_group"] => string(0) ""
    ["uploadedFiles"] => string(0) ""
    ["uploadedFileName"] => string(0) ""
    ["title"] => string(19) "Sample problem"
  }`  

Does anyone know how to sort this by status the status can be a number from 1 to 5

Edit: So far i've attempted these solutions

function natorder($a,$b) { 
   return strnatcmp ( $a['status'],  $b['status'] ); 
} 

uasort ($array, 'natorder');  

from: http://board.phpbuilder.com/showthread.php?10244548-natsort()-on-a-multidimensional-array

usort($myArray, function($a, $b) {
    return $a['order'] - $b['order'];
});

from: Sort Multi-dimensional Array by Value

I'm using php 7 if anyone is wondering.


Solution

  • try usort($array, function($a, $b) { return $a['status'] <=> $b['status'];})

    tested using:

    [
     [
       "name" => "a",
       "status" => "2",
     ],
     [
       "name" => "b",
       "status" => "4",
     ],
     [
       "name" => "c",
       "status" => "1",
     ],
     [
       "name" => "d",
       "status" => "3",
     ],
    

    ]

    which outputs

    [
     [
       "name" => "c",
       "status" => "1",
     ],
     [
       "name" => "a",
       "status" => "2",
     ],
     [
       "name" => "d",
       "status" => "3",
     ],
     [
       "name" => "b",
       "status" => "4",
     ],
    

    ]

    after you run the

    usort($array, function($a, $b) { return $a['status'] <=> $b['status'];})