繁体   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