鉴于此数组:
Array
(
[0] => Array
(
[title] => this is the newest post
[ssm_featured_post_id] => 70
)
[1] => Array
(
[title] => sdfsfsdf
[ssm_featured_post_id] => 63
)
[2] => Array
(
[title] => test
[ssm_featured_post_id] => 49
)
[3] => Array
(
[title] => Hello world!
[ssm_featured_post_id] => 1
)
)
将另一个类似数组与新值合并的最简单方法是什么。
第二个数组可能包含新项目或已删除项目。
我想保留第一个数组中项目的顺序,并将所有新项目添加到最后,并删除不在新数组中的任何项目
Array
(
[0] => Array
(
[title] => sdfsfsdf
[ssm_featured_post_id] => 63
)
[1] => Array
(
[title] => this is the newest post
[ssm_featured_post_id] => 70
)
[2] => Array
(
[title] => test
[ssm_featured_post_id] => 49
)
[3] => Array
(
[title] => Hello world!
[ssm_featured_post_id] => 1
)
[4] => Array
(
[title] => awesome post
[ssm_featured_post_id] => 73
)
)
答案 0 :(得分:1)
您可以使用功能uasort,它允许您实现自己的比较功能
function cmp($a, $b) {
if ($a['ssm_featured_post_id'] == $b['ssm_featured_post_id']) {
return 0;
}
return ($a['ssm_featured_post_id'] < $b['ssm_featured_post_id']) ? -1 : 1;
}
uasort($array, 'cmp');
通过传递数组
来删除重复项目扫描重复项目$last_id=-1;
for($i=0; $i < cout($array); $i++){
if($last_id==$array[$i]['ssm_featured_post_id']){
unset($array[$i]);//Remove Duplicated Item
}
$last_id=$array[$i]['ssm_featured_post_id'];
}
答案 1 :(得分:0)
使用array_merge,因为键是数字。 “如果输入数组具有相同的字符串键,则该键的后一个值将覆盖前一个键。但是,如果数组包含数字键,则后面的值不会覆盖原始值” http://php.net/manual/en/function.array-merge.php
答案 2 :(得分:0)
好吧,因为我需要针对数组1检查数组2并合并数组2中的任何新内容,这个解决方案似乎有效:
$new_values = array_merge( $slides, $featured_posts );
$new_values = array_unique( $new_values, SORT_REGULAR );