簡體   English   中英

對數組值與另一個數組的鍵匹配的數組進行排序

[英]Sort array where array value matches another array's keys

我有2個數組,其中1個保存要顯示的數據,另一個保存順序。

以下數組將在foreach循環中用於顯示:

array(
   [Posts] =>
            [0] =>
                 id => 7
                 content => 'some content'
            [1] =>
                 id => 3,
                 content => 'some other content'
            [2] =>
                 id => 4,
                 content => 'some more content'
            [3] =>
                 id => 2,
                 content => 'some irrelevant content'
)

該數組包含排序位置:

array(
   2, 4, 7, 3
)

我想基於鍵值是與第二個數組匹配的id的關聯數組中的值對第一個數組進行排序。

預期產量:

array(
   [Posts] =>
            [0] =>
                 id => 2,
                 content => 'some irrelevant content'
            [1] =>
                 id => 4,
                 content => 'some more content'
            [2] =>
                 id => 7
                 content => 'some content'
            [3] =>
                 id => 3,
                 content => 'some other content'
)

如果源數組鍵等於ID,則可以極大地幫助自己。 這樣可以加快速度。 但是現在這將使您的源數據根據您的排序數組值排序):

$res = array();
foreach( $sortArray as $sortId ) {
   foreach( $srcArray as $item ) {
      if( $item['id'] == $sortId ) {
         $res = $item;
         break;
      }
   }
}

編輯

如果您將Id用作鍵,則第二個foreach()foreach()

$res = array();
foreach( $sortArray as $sortId ) {
   $res[] = $srcArray[ $sortId ];
}

此解決方案使用usort

$sarray = array(2, 4, 7, 3);
$sarray = array_flip($sarray);

usort($posts, function($a, $b) use($sarray) {
    // TODO: check if the array-index exists ;)
    $index_a = $sarray[$a['id']];
    $index_b = $sarray[$b['id']];

    return $index_a - $index_b;
});

var_dump($posts);

由於我使用的是閉包,因此需要PHP 5.3來使用它。 如果需要5.2兼容性,則可能必須使用create_function

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM