我有两个简单的数组。一个是一系列帖子($ posts),另一个是一系列帖子ID,应该在流的顶部,就像它们的特色($特色)一样。我试图找到一种循环它们的有效方法,如果ID在两个数组中,则将其移动到$ posts数组的开头,并且移动的那些应该按$ feature ['订单'],例如,一些帖子($帖子):
Array
(
[ab77] => Status_Update Object
(
[id] => ab77
[title] => Status Update
)
[b4k7] => Status_Update Object
(
[id] => b4k7
[title] => Status Update
)
[4d55] => Status_Update Object
(
[id] => 4d55
[title] => Status Update
)
[13c5] => Status_Update Object
(
[id] => 13c5
[title] => Status Update
)
[3aa2] => Status_Update Object
(
[id] => 3aa2
[title] => Status Update
)
)
然后是一些应该推荐的帖子($ feature):
Array
(
[13c5] => Array
(
[id] => 13c5
[order] => 1
)
[3a71] => Array
(
[id] => 3a71
[order] => 2
)
[4d55] => Array
(
[id] => 4d55
[order] => 3
)
)
所以$ posts数组应该像这样排序:
13C5 4d55 ab77 bk47 3aa2
如果没有一堆慢循环,我该怎么做?
答案 0 :(得分:3)
uksort( $posts, function ( $a, $b ) use ( $featured ) {
$fa = ( isset( $featured[$a] ) ? $featured[$a]['order'] : INF );
$fb = ( isset( $featured[$b] ) ? $featured[$b]['order'] : INF );
if ( $fa != $fb ) return ( $fa < $fb ? -1 : +1 );
// could add a tie-breaker comparison here
return 0;
} );
答案 1 :(得分:0)
这是我提出作品的凌乱答案。
$found, $not_found = array();
foreach ($posts as $key => $value) {
if (array_key_exists($key, $featured)) {
$found[$key] = $value;
} else {
$not_found[$key] = $value;
}
}
usort($found, 'sort_by_order');
function sort_by_order ($a, $b) {
return $a['order'] - $b['order'];
}
$new = array_merge($found, $not_found);