根据postID删除重复数据

时间:2016-08-29 06:23:18

标签: php multidimensional-array

我有一个如下数组:

Array
(
    [0] => Array
        (
            [postId] => 105
            [postTitle] => Test
            [postNonArray] => Subzero
            [postDesc] => Array
                (
                    [0] => Array
                        (
                            [para] => Subzero
                            [align] => L
                        )

                )

            [postDate] => 25.08.2016
            [postTime] => 13:44
            [postImage] => http://testyourprojects.biz/custom/ci/tharjumal/uploads/post/post_1472112857.png
            [postVideo] => 
        )

    [1] => Array
        (
            [postId] => 106
            [postTitle] => Test 2
            [postNonArray] => Test
            [postDesc] => Array
                (
                    [0] => Array
                        (
                            [para] => Test
                            [align] => L
                        )

                )

            [postDate] => 26.08.2016
            [postTime] => 18:08
            [postImage] => http://testyourprojects.biz/custom/ci/tharjumal/uploads/post/post_1472215085.jpg
            [postVideo] => 
        )

    [2] => Array
        (
            [postId] => 106
            [postTitle] => Test 2
            [postNonArray] => Test
            [postDesc] => Array
                (
                    [0] => Array
                        (
                            [para] => Test
                            [align] => L
                        )

                )

            [postDate] => 26.08.2016
            [postTime] => 18:08
            [postImage] => http://testyourprojects.biz/custom/ci/tharjumal/uploads/post/post_1472215085.jpg
            [postVideo] => 
        )

)

如您所见,postId=106;有两个帖子详细信息 如何根据postId

从阵列中删除冗余数据

项目在PHP上。

3 个答案:

答案 0 :(得分:4)

我认为这是你想要实现的目标: -

$array = array_map("unserialize", array_unique(array_map("serialize", $array)));
echo "<pre/>";print_r($array);

检查输出(整个代码与原始数组): - https://eval.in/630678

注意: - 它将删除重复的值(因此整个重复数组将按照您在评论中的要求消失)

答案 1 :(得分:1)

您需要循环数据并创建一个具有唯一值的新数组,所以请转到:

$ShowNewArray = array();
foreach($array as $key => $value){
  if(!array_key_exists('postId', $ShowNewArray)){
    $ShowNewArray[$value['postId']] = $value;
  }
}

print_r($ShowNewArray);

希望它会对你有所帮助。

答案 2 :(得分:1)

我建议循环如下。它将遍历$ your_array_name中的所有元素,并将创建一个唯一的id数组,我们将存储postIds。我们还将检查$ unique_ids数组中是否有重复项,如果是,我们将删除该重复元素。

$unique_ids = array();
foreach($your_array_name as $key => $value){
  //check if the postId is in the array of the unique ids
  if(!in_array($value['postId'], $unique_ids)()){
    array_push($unique_ids,$value['postId']); //if it is not - push it there
  } else {
    unset($your_array_name($key)); //if it is - remove the whole element from the array
  }
}