I have this array
Array (
[0] => Array ( [name] => Apple [amount] => 1)
[1] => Array ( [name] => Apple [amount] => 2)
[2] => Array ( [name] => Orange [amount] => 3)
[3] => Array ( [name] => Orange [amount] => 4)
[4] => Array ( [name] => Banana [amount] => 5)
[5] => Array ( [name] => Pear [amount] => 6)
)
Which I would like to end up like this:
Array (
[0] => Array ( [name] => Apple [amount] => 1)
[2] => Array ( [name] => Orange [amount] => 3)
[4] => Array ( [name] => Banana [amount] => 5)
[5] => Array ( [name] => Pear [amount] => 6)
)
The important thing is that the array key values must be the same after transforming.
At the moment I use this solution:
$newArray = array();
$usedFruits = array();
foreach ( $originalArray AS $line ) {
if ( !in_array($line['name'], $usedFruits) ) {
$usedFruits[] = $line['name'];
$newArray[] = $line;
}
}
$originalArray = $newArray;
$newArray = NULL;
$usedFruits = NULL;
This removes the duplicate arrays but it also resets the key values.
Array (
[0] => Array ( [name] => Apple [amount] => 1)
[1] => Array ( [name] => Orange [amount] => 3)
[2] => Array ( [name] => Banana [amount] => 5)
[3] => Array ( [name] => Pear [amount] => 6)
)
How is it possible to keep the original array key values?
Use the optional $key
in the foreach()
:
foreach ( $originalArray AS $key => $line ) {
if ( !in_array($line['name'], $usedFruits) ) {
$usedFruits[] = $line['name'];
$newArray[$key] = $line;
}
}
http://codepad.org/SuClGlQW
Outputs:
Array
(
[0] => Array
(
[name] => Apple
[amount] => 1
)
[2] => Array
(
[name] => Orange
[amount] => 3
)
[4] => Array
(
[name] => Banana
[amount] => 5
)
[5] => Array
(
[name] => Pear
[amount] => 6
)
)
All You had to use is the unset function.
unset function removes an item from array at specified index without rebasing the array index.
code will be as follows
$originalArray = array(
array("name" => "Apple", "amount" => 1),
array("name" => "Apple", "amount" => 2),
array("name" => "Orange", "amount" => 3),
array("name" => "Orange", "amount" => 4),
array("name" => "Banana", "amount" => 5),
array("name" => "Peer", "amount" => 6)
);
$seenItems = array();
foreach($originalArray as $index => $item){
if(in_array($item["name"], $seenItems))
unset($originalArray[$index]);
else
$seenItems[] = $item["name"];
}
and the output will be as follows
array(4) {
[0]=>
array(2) {
["name"]=>
string(5) "Apple"
["amount"]=>
int(1)
}
[2]=>
array(2) {
["name"]=>
string(6) "Orange"
["amount"]=>
int(3)
}
[4]=>
array(2) {
["name"]=>
string(6) "Banana"
["amount"]=>
int(5)
}
[5]=>
array(2) {
["name"]=>
string(4) "Peer"
["amount"]=>
int(6)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With