php - Struggling to sort a muldimensional associative array -
i have spent long time looking through forums, cannot work.
i have multidimensional, assoctaive array (in class). declared as:
protected $issnlookup = array();
in function, (to populate array data source):
foreach($this->keys $k) { $issn = $this->getissn($k); if($issn != '') { // publication has 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 display array contents, using:
foreach($this->issnlookup $key => $value) { echo $key . ' (' . $value['journal'] . '): ' . $value['number'] . '</br>'; }
... looks good. (this sample):
0924-669x (applied intelligence): 3 1943-068x (ieee transactions on computational intelligence , ai in games): 6 1000-9000 (journal of computer science , technology): 1 0377-2217 (european journal of operational research): 8 0020-7721 (international journal of systems science): 1 1619-4500 (4or - quarterly journal of operations research): 2 0160-5682 (journal of operational research society): 11
if sort, using
usort($this->issnlookup, array($this, 'issnlookupjournalnamesort'));
with function (to compare values):
function issnlookupjournalnamesort($a, $b) { return strcmp($a['journal'], $b['journal']); }
and display again (using same code above), get:
0 (4or - 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. names sorted - has happened 9-char id? seems have reverted counter
any appreciated.
the answer simple, use uasort
:
uasort
— sort array user-defined comparison function , maintain index association
uasort($this->issnlookup, array($this, 'issnlookupjournalnamesort'));
additional info on sorting methods http://php.net/manual/en/array.sorting.php.
wiki
Comments
Post a Comment