PHP remove duplicate key or value in multidimensional array

Example this multidimensional array having duplicate retailer_id, and we want no duplicate of retailer id in the array although it keep different id information:

$newArray = array(
	[9] =>Array(
		[id] => 137584179106fjuyp
		[retailer_id] => 137583939533rhfhe
	)
	[23] => Array(
		[id] => 137584506132hbjoi
		[retailer_id] => 137583962056xznqi
	)
	[18] => Array(
		[id] => 137584425754yantn
		[retailer_id] => 137583952995tqfhg
	)
	[3] => Array(
		[id] => 137584077579soocg
		[retailer_id] => 137583971485ogdkz
	)
	[17] => Array(
		[id] => 137584414660doyer
		[retailer_id] => 137583962056xznqi
	)
	[8] => Array(
		[id] => 137584169405xcxsf
		[retailer_id] => 137583939533rhfhe
));

To clean above:

//remove duplicate retailer_id array
$outputArray = array(); // The results will be loaded into this array.
$keysArray = array(); // The list of keys will be added here.
foreach ($newArray as $innerArray) { // Iterate through sorted main array.
if (!in_array($innerArray['retailer_id'], $keysArray)) { // Check to see if retailer_id already been used before.
$keysArray[] = $innerArray['retailer_id']; // If retailer_id hasn't been used before, add it into the list of keys.
$outputArray[] = $innerArray; // Add the inner array into the output.
}
}

$outputArray is the final clean array.

If we want to remove existing key from an array:
simply:

//filter away existing coupon, remove by id
foreach ($newArray as $key=>$innerArray) { // Iterate through sorted main array.
	if($newArray['exist_id'] == $innerArray['id']) {
	unset($newArray[$key]);
}
}

By Keenlio, April 15, 2014

2 Comments

  1. providing that the services offered have adequate demand. says:

    providing that the services offered have adequate demand.

  2. PatriciaKabe says:

    Great article! We will be linking to this particularly great article on our website. Keep up the good writing.

What do you think?

Leave a Reply

Your email address will not be published. Required fields are marked *


five × = 10

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>