给定此数组:
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
)
)发布于 2012-10-31 05:42:08
您可以使用函数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'];
}发布于 2012-10-31 05:40:45
使用array_merge,因为键是数字的。“如果输入数组具有相同的字符串键,则该键的后一个值将覆盖前一个值。但是,如果数组包含数字键,则后一个值不会覆盖原始值”http://php.net/manual/en/function.array-merge.php
发布于 2012-10-31 08:34:21
嗯,因为我需要检查Array 2和array 1,并合并来自array 2的任何新内容,所以这个解决方案似乎是有效的:
$new_values = array_merge( $slides, $featured_posts );
$new_values = array_unique( $new_values, SORT_REGULAR );https://stackoverflow.com/questions/13147903
复制相似问题