Get unique array values in multi-dimensional associate array php

Php
Jan 02 2017
2303 Views

Get unique array values in multi-dimensional associate array php

Introduction

If you need to get array unique values from array use “array_unique” function. But while dealing with multi-dimensional associate array, this “array_unique” will not work. Use bellow function to get unique values from associate array.

Description

Use this function to get unique values from associate array. Click here to read about array_map function.

function get_unique_associate_array($array) {

                $serialized_array = array_map("serialize", $array);

                foreach ($serialized_array as $key => $val) {

                     $result[$val] = true;

                }

                return array_map("unserialize", (array_keys($result)));

}

Example Code

<?

$arr = array(

    "1" => array(

         "name" => "Abc",

         "phone" => "123456"

    ),

    "2" => array(

         "name" => "Def",

         "phone" => "123456"

    ),

    "3" => array(

         "name" => "Abc",

         "phone" => "123456"

    ),

    "4" => array(

         "name" => "Def",

         "phone" => "456789"

    )

);

 

//Original array output

echo "<pre>"; print_r($arr);

 

$arr2 = get_unique_associate_array($arr);

 

//Unique array

echo "<pre>"; print_r($arr2);

 

function get_unique_associate_array($array) {

                $serialized_array = array_map("serialize", $array);

                foreach ($serialized_array as $key => $val) {

                     $result[$val] = true;

                }

                return array_map("unserialize", (array_keys($result)));

}

?>

Leave a Reply