Reputation: 6683
I have an array which contains multiple of the same data:
array(2) {
[0]=>
array(2) {
["id"]=>
string(11) "43000173601"
["data"]=>
array(2) {
[0]=>
array(2) {
["id"]=>
string(5) "52874"
["name"]=>
string(3) "x70"
}
[1]=>
array(2) {
["id"]=>
string(5) "52874"
["name"]=>
string(3) "x70"
}
}
}
[1]=>
array(2) {
["id"]=>
string(11) "43000173602"
["data"]=>
array(1) {
[0]=>
array(2) {
["id"]=>
string(5) "52874"
["name"]=>
string(3) "x70"
}
}
}
}
I have tried using array_unique()
to remove these entries, but receive this error:
Array to string conversion
The outer arrays contain route ID's, some busses may have 2 different routes so in this case, they can stay however, I just want to remove the dupe entries inside the 1 route:
[0]=>
array(2) {
["id"]=>
string(11) "43000173601"
["data"]=>
array(2) {
[0]=>
array(2) {
["id"]=>
string(5) "52874"
["name"]=>
string(3) "x70"
}
[1]=>
array(2) {
["id"]=>
string(5) "52874"
["name"]=>
string(3) "x70"
}
}
Upvotes: 0
Views: 286
Reputation: 6683
I fixed it by doing this:
$stripped = [];
foreach($arr as $single) {
$stripped[] = ['id' => $single['id'], 'data' => array_unique($single['data'])];
}
Since the duplicates existed inside the inner arrays, not the outer array, I had to use array_unique()
on the inner arrays.
Upvotes: 1
Reputation: 23958
You can use array_column to make the array associative. That will remove any duplicates.
Array_values will then remove the associative and make it normal indexed array again.
Rsort makes sure you get the lowest key as the result array.
rsort($arr);
$arr = array_values(array_column($arr, Null, "id"));
Upvotes: 1
Reputation: 54831
Code can be something like this:
$new_array = [];
foreach ($your_array as $item) {
if (!isset($new_array[$item['id']])) {
// item id is not in `new_array` - add `item`
$new_array[$item['id']] = $item;
} else {
// item id already presents - add `data` item to it
$new_array[$item['id']]['data'][] = $item['data'];
}
}
Upvotes: 1