Reputation: 73221
I have this array:
$array[] = [
'a' => $a,
'b' => $b,
];
The array contains of let's say 10 entries, $a can be in there with the same value many times and I need only one of those entries for a db insert.
I can't manage to get array_unique working as it throws
array to string conversion
error when trying to use it like
$result = array_unique($array);
I now made a little foreach loop that feels just wrong to do so:
$z = [];
foreach ($array as $x) {
if (@!in_array($x['a'],$z)) {
$z[] = $x['a'];
}
}
and I use $z for the insert thereafter.
Can someone point me in the right direction of how to distinct my array values?
Upvotes: 2
Views: 67
Reputation: 21661
One thing not mentioned is that arrays are built in unique, if you can manage the keys for them yourself. Associative arrays can only have the key once. So I like to do is use the primary key or a unique identifier for the key.
You can't have an array with the same keys like this.
array(
'a' => $a
'a' => $b
)
Because the key a
is already a unique identifier. If you follow.
Upvotes: 0
Reputation: 59681
This should work for you:
($result = array_unique($array);
this didn't worked, because you have a multidimensional array!)
<?php
//Example data
$array[] = [
'a' => 1,
'b' => 1,
'c' => 1,
'd' => 2,
'e' => 2,
];
$array = array_map("array_unique", $array);
print_r($array);
?>
Output:
Array ( [0] => Array ( [a] => 1 [d] => 2 ) )
Upvotes: 3
Reputation: 78994
Based on your array that is two dimensional, you would need:
$array = array_map('array_unique', $array);
Or if you don't need a two dimensional array, just use:
$array = [
'a' => $a,
'b' => $b,
];
And then: $array = array_unique($array);
Upvotes: 1