苦苦挣扎着对多维关联数组进行排序

苦苦挣扎着对多维关联数组进行排序

问题描述:

I have spent a long time looking through the forums, but just cannot get this to work.

I have a multidimensional, assoctaive array (in a class). It is declared as:

protected $ISSNLookup = array();

In a function, I say (to populate the array from another data source):

foreach($this->keys as $k) {
    $issn = $this->getISSN($k);
    if($issn != '') { // This publication has an ISSN
       if(array_key_exists($issn, $this->ISSNLookup)) {
           $this->ISSNLookup[$issn]['number']++;
       }
       else {
           $addItem = array( 'journal' => $this->getJournal($k), 'number' => 1);
           $this->ISSNLookup[$issn] = $addItem;
       } // else, key not on $ISSNLookup
    } // if $issn != ''
} // foreach

If I then display the array contents, using:

foreach($this->ISSNLookup as $key => $value) {
  echo $key . ' (' . $value['journal'] . '): ' . $value['number'] . '</br>';
}

... all looks good. That is (this is just a sample):

0924-669X (Applied Intelligence): 3

1943-068X (IEEE Transactions on Computational Intelligence and AI in Games): 6

1000-9000 (Journal of Computer Science and Technology): 1

0377-2217 (European Journal of Operational Research): 8

0020-7721 (International Journal of Systems Science): 1

1619-4500 (4OR - A Quarterly Journal of Operations Research): 2

0160-5682 (Journal of the Operational Research Society): 11

If I now sort, using

usort($this->ISSNLookup, array($this, 'ISSNLookupJournalNameSort'));

with the function (to compare the values):

function ISSNLookupJournalNameSort($a, $b) {
    return strcmp($a['journal'], $b['journal']);
}

and display again (using the same code as above), I get:

0 (4OR - A Quarterly Journal of Operations Research): 2

1 (Advances in Econometrics): 1

2 (Annals of Operations Research): 3

3 (Applied Intelligence): 3

4 (Applied Soft Computing): 3

5 (Artificial Life): 1

The sort has worked (i.e. the names are sorted - but what has happened to the 9-char ID? It seems to have reverted to a counter

Any help appreciated.

The answer is simple, use uasort:

uasort — Sort an array with a user-defined comparison function and maintain index association

uasort($this->ISSNLookup, array($this, 'ISSNLookupJournalNameSort'));

Additional info on sorting methods http://php.net/manual/en/array.sorting.php.