您可以编写一个递归函数来提取下一个可用的位置编号,但如果您正在处理少量的帖子 + 广告,则类似下面的内容会快速而简单。请注意,这假设您需要保留 ads 和 posts 数组的原始键。如果您不需要这样做,那么您可以进一步简化它。
// Sample array of ads
$ads = array('ad1' => array('position' => 1),
'ad2' => array('position' => 4),
'ad3' => array('position' => 6),
'ad4' => array('position' => 10));
// Identify ad positions
foreach ( $ads as $k => $v ) {
$adPositions[$v['position']] = $v['position'];
}
// Identify available positions
$availablePositions = array_combine(range(1,100), range(1,100));
$availablePositions = array_diff_key($availablePositions, $adPositions);
// Sample posts
$posts = array('post1' => array('position' => false),
'post2' => array('position' => false),
'post3' => array('position' => false),
'post4' => array('position' => false),
'post5' => array('position' => false),
'post6' => array('position' => false));
// Use first (lowest number) available position as post position
foreach ( $posts as $k => $v ) {
$posts[$k]['position'] = array_shift($availablePositions);
}
// Merge arrays
$merged = array_merge($ads, $posts);
// Create list of positions for use with array_multisort
foreach ( $merged as $k => $v ) {
$position[$k] = $v['position'];
}
// Sort $merged by ['position']
array_multisort($position, SORT_ASC, $merged);
给你:
Array
(
[ad1] => Array
(
[position] => 1
)
[post1] => Array
(
[position] => 2
)
[post2] => Array
(
[position] => 3
)
[ad2] => Array
(
[position] => 4
)
[post3] => Array
(
[position] => 5
)
[ad3] => Array
(
[position] => 6
)
[post4] => Array
(
[position] => 7
)
[post5] => Array
(
[position] => 8
)
[post6] => Array
(
[position] => 9
)
[ad4] => Array
(
[position] => 10
)
)