dongyanju0945 2017-08-22 14:52
浏览 42
已采纳

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

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.

  • 写回答

1条回答 默认 最新

  • donvo24600 2017-08-22 14:56
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试