Westley Knight
Westley Knight

Reputation: 25

How to sort a multi-dimensional array by a 4th level value in PHP

I have an array which is converted from an XML response. What I need to do is sort the array ascending alphabetically using the 'COMPANY' value.

I have attempted to use array_multisort, but I'm having no luck at all. Any help would be greatly appreciated.

Here is the array:

array(1) {
  ["DATASOURCE"]=>
  array(1) {
    ["MEMBER"]=>
    array(4) {
      [0]=>
      array(4) {
        ["REFNO"]=>
        string(6) "000762"
        ["STATUS"]=>
        string(5) "CURRE"
        ["DATE"]=>
        string(8) "20100731"
        ["COMPANY"]=>
        string(80) "Tresham Institute Business Solutions                                            "
      }
      [1]=>
      array(4) {
        ["REFNO"]=>
        string(6) "003721"
        ["STATUS"]=>
        string(5) "CURRE"
        ["DATE"]=>
        string(8) "20100930"
        ["COMPANY"]=>
        string(80) "Triad esign                                                                    "
      }
      [2]=>
      array(4) {
        ["REFNO"]=>
        string(6) "011412"
        ["STATUS"]=>
        string(5) "CURRE"
        ["DATE"]=>
        string(8) "20100630"
        ["COMPANY"]=>
        string(80) "Transpower Drives Ltd                                                           "
      }
      [3]=>
      array(4) {
        ["REFNO"]=>
        string(6) "059647"
        ["STATUS"]=>
        string(5) "CURRE"
        ["DATE"]=>
        string(8) "20100630"
        ["COMPANY"]=>
        string(80) "Trek-Kits Ltd                                                                   "
      }
    }
  }
}

Upvotes: 0

Views: 1569

Answers (2)

Karthik
Karthik

Reputation: 3281

You can use usort() PHP function.

Upvotes: 0

cHao
cHao

Reputation: 86525

You'll need a function that takes the two items to be sorted, and compares them.

function sort_by_company($a, $b)
{
    return strcmp($a['COMPANY'], $b['COMPANY']);
}

Then, use the usort function.

usort($arr['DATASOURCE']['MEMBER'], 'sort_by_company');

Upvotes: 6

Related Questions