note 116302 modified in function.array-unique by levim

From: Date: Sun, 20 Dec 2015 05:55:35 +0000
Subject: note 116302 modified in function.array-unique by levim
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-204503@lists.php.net to get a copy of this message
Create multidimensional array unique for any single key index. e.g I want to create multi dimentional unique array for specific code Code : My array is like this, <?php $details = array( 0 => array("id"=>"1", "name"=>"Mike", "num"=>"9876543210"), 1 => array("id"=>"2", "name"=>"Carissa", "num"=>"08548596258"), 2 => array("id"=>"1", "name"=>"Mathew", "num"=>"784581254"), ); ?> You can make it unique for any field like id, name or num. I have develop this function for same : <?php function unique_multidim_array($array, $key) { $temp_array = array(); $i = 0; $key_array = array(); foreach($array as $val) { if (!in_array($val[$key], $key_array)) { $key_array[$i] = $val[$key]; $temp_array[$i] = $val; } $i++; } return $temp_array; } ?> Now, call this function anywhere from your code, something like this, <?php $details = unique_multidim_array($details,'id'); ?> Output will be like this : <?php $details = array( 0 => array("id"=>"1","name"=>"Mike","num"=>"9876543210"), 1 => array("id"=>"2","name"=>"Carissa","num"=>"08548596258"), ); ?> --was-- Create multidimensional array unique for any single key index. e.g I want to create multi dimentional unique array for specific code Code : My array is like this, <?php $details = array( [0]=>array("id"=>"1","name"=>"Mike","num"=>"9876543210"), [1]=>array("id"=>"2","name"=>"Carissa","num"=>"08548596258"), [2]=>array("id"=>"1","name"=>"Mathew","num"=>"784581254"), ); ?> you can make it unique for any field like id, name or num. I have develop this function for same : <?php function unique_multidim_array($array, $key){ $temp_array = array(); $i = 0; $key_array = array(); foreach($array as $val){ if(!in_array($val[$key],$key_array)){ $key_array[$i] = $val[$key]; $temp_array[$i] = $val; } $i++; } return $temp_array; } ?> Now, call this function anywhere from your code, something like this, <?php $details = unique_multidim_array($details,'id'); ?> Output will be like this : <?php $details = array( [0]=>array("id"=>"1","name"=>"Mike","num"=>"9876543210"), [1]=>array("id"=>"2","name"=>"Carissa","num"=>"08548596258"), ); ?> http://php.net/manual/en/function.array-unique.php

« previous php.notes (#204503) next »