Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Take the first element if exist

I have a collection that contain two arrays :

array:2 [
  0 => array:3 [
 
    "Code" => "AKAR02"
    "startDate" => "2022-10-27"
    "endDate" => null
  ]
  1 => array:3 [
    "Code" => "AKAR02"
    "startDate" => "2022-10-27"
    "endDate" => null
  ]
]
  1. take the first element if they have the same code & the same start date
  2. if they have different startDate take the most recent one

i tried the ->contains method but is not working

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This feels like an odd use case but this should get you on the right track:

$sameElements = [
    [
        "Code" => "AKAR02",
        "startDate" => "2022-10-27",
        "endDate" => null,
    ],
    [
        "Code" => "AKAR02",
        "startDate" => "2022-10-27",
        "endDate" => null,
    ]
];

$collection = collect($sameElements);
[$first, $second] = $collection->only(0, 1);

if (
    $first['code'] === $second['code']
    && $first['startDate'] === $second['endDate']
) {
    // take the first element if they have the same code & the same start date
} else {
    // do something else?
}

//if they have different startDate take the most recent one
$diffElements = [
    [
        "Code" => "AKAR02",
        "startDate" => "2022-10-27",
        "endDate" => null,
    ],
    [
        "Code" => "AKAR02",
        "startDate" => "2022-10-01",
        "endDate" => null,
    ]
];

$collection = collect($diffElements);
[$first, $second] = $collection->only(0, 1);

// if they have different startDate take the most recent one
if ($first['startDate'] != $second['startDate']) {
    // do something with the most recent one
    $mostRecent = $collection->sort(function ($a, $b) {
        return strtotime($a['startDate']) <=> strtotime($b['startDate']);
    })->first();
} else {
    // do something else
}

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading