苦苦挣扎着对多维关联数组

时间:2017-08-22 14:52:46

标签: php arrays sorting associative-array

我花了很长时间浏览论坛,但却无法让它发挥作用。

我有一个多维的,关联的数组(在一个类中)。它被声明为:

protected $ISSNLookup = array();

在一个函数中,我说(从另一个数据源填充数组):

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

如果我然后显示数组内容,请使用:

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

......一切看起来都不错。那是(这只是一个例子):

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

如果我现在使用

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

使用函数(比较值):

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

再次显示(使用与上面相同的代码),我得到:

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

排序有效(即名称已排序 - 但9-char ID发生了什么?似乎已经恢复到计数器

任何帮助表示感谢。

1 个答案:

答案 0 :(得分:2)

答案很简单,请使用uasort

  

uasort - 使用用户定义的比较函数对数组进行排序,维护索引关联

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

有关排序方法的其他信息http://php.net/manual/en/array.sorting.php