'produce a new array or collection based on certain condition
can anyone help me with this query of duplication? how can i produce a new array or collection based on certain condition that matches and keep other records as same. e.g in the following array, i want to move all duplication, which start, end date and provider is same?
$array=[
[
'id' => 1,
'start_date' => '2022-04-08',
'end_date' => '2022-05-08',
'provider' => 'abc'
],
[
'id' => 2,
'start_date' => '2022-04-08',
'end_date' => '2022-05-08',
'provider' => 'abc'
],
[
'id' => 4,
'start_date' => '2022-04-08',
'end_date' => '2022-05-08',
'provider' => 'abc'
],
[
'id' => 3,
'start_date' => '2022-05-08',
'end_date' => '2022-06-08',
'provider' => 'xyz'
],
[
'id' => 5,
'start_date' => '2022-05-08',
'end_date' => '2022-06-08',
'provider' => 'xyz'
],
[
'id' => 6,
'start_date' => '2022-05-09',
'end_date' => '2022-06-10',
'provider' => 'xyz'
],
];
expected output, the duplicate means, this is kind of same ticket, provided by different providers, so i need to have them together
$expectedArray = [
'duplicates' => [
[
'id' => 1,
'start_date' => '2022-04-08',
'end_date' => '2022-05-08',
'provider' => 'abc'
],
[
'id' => 2,
'start_date' => '2022-04-08',
'end_date' => '2022-05-08',
'provider' => 'abc'
],
[
'id' => 4,
'start_date' => '2022-04-08',
'end_date' => '2022-05-08',
'provider' => 'abc'
],
],
'duplicates' => [
[
'id' => 3,
'start_date' => '2022-05-08',
'end_date' => '2022-06-08',
'provider' => 'xyz'
],
[
'id' => 5,
'start_date' => '2022-05-08',
'end_date' => '2022-06-08',
'provider' => 'xyz'
],
],
[
'id' => 6,
'start_date' => '2022-05-09',
'end_date' => '2022-06-10',
'provider' => 'xyz'
],
];
Solution 1:[1]
Try this....
$array = [
[
'id' => 1,
'start_date' => '2022-04-08',
'end_date' => '2022-05-08',
'provider' => 'abc'
],
[
'id' => 2,
'start_date' => '2022-04-08',
'end_date' => '2022-05-08',
'provider' => 'abc'
],
[
'id' => 3,
'start_date' => '2022-05-08',
'end_date' => '2022-06-08',
'provider' => 'xyz'
],
];
foreach ($array as $key => &$entry) {
if($entry['provider']=='abc'){ $expectedArray[0]['duplicates'][$key] = $entry;}else{ $expectedArray[] = $entry;}
}
print_r($expectedArray);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Manikandan G |
