0

给定这个数组:

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
    )

)
4

3 回答 3

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'];
}
于 2012-10-30T21:42:07.577 回答
0

好吧,因为我需要检查数组 2 和数组 1 并合并数组 2 中的任何新内容,所以这个解决方案似乎有效:

$new_values = array_merge( $slides, $featured_posts );
$new_values = array_unique( $new_values, SORT_REGULAR );
于 2012-10-31T00:34:21.293 回答
0

使用 array_merge 因为键是数字的。“如果输入数组具有相同的字符串键,则该键的后一个值将覆盖前一个。但是,如果数组包含数字键,则后一个值不会覆盖原始值” http://php.网络/手册/en/function.array-merge.php

于 2012-10-30T21:40:45.320 回答