I have a array : $data
.
And this is the result when I dd($data)
array(3) { [0]=> array(4) { ["order"]=> int(3) ["userId"]=> string(36) "b3cef82a-ab65-4a0f-9e4b-3ad1d0324532" ["createdAt"]=> string(24) "2021-09-24T03:29:37.000Z" ["updatedAt"]=> string(24) "2021-09-24T03:29:37.000Z" } [1]=> array(4) { ["order"]=> int(2) ["userId"]=> string(36) "2955e28b-4d26-4992-9b5e-b300529dsas3" ["createdAt"]=> string(24) "2021-09-24T03:22:32.000Z" ["updatedAt"]=> string(24) "2021-09-24T03:22:32.000Z" } [2]=> array(4) { ["order"]=> int(3) ["userId"]=> string(36) "wert5678-b85c-4802-b53f-cbdfe9515ty6b" ["createdAt"]=> string(24) "2021-09-01T10:13:45.000Z" ["updatedAt"]=> string(24) "2021-09-01T10:13:45.000Z" } }
In controller :
$dataReal = ''; foreach ($data as $v) { if($v['order'] == 3) { $dataReal = $v; } } dd($dataReal);
Result :
array(4) { ["order"]=> int(3) ["userId"]=> string(36) "wert5678-b85c-4802-b53f-cbdfe9515ty6b" ["createdAt"]=> string(24) "2021-09-01T10:13:45.000Z" ["updatedAt"]=> string(24) "2021-09-01T10:13:45.000Z" }
In my array. I have two order = 3
. I just want to get an array with order = 3
and have the latest time. For example, I want to get an array with order = 3
and createAt = '2021-09-24T03:29:37.000Z'
Advertisement
Answer
try this solution it will help
$dataReal = ''; foreach ($data as $v) { if($v['order'] == 3) { if(is_null($dataReal)) { $dataReal = $v; } else { if(strtotime($v["createdAt"]) > strtotime($dataReal["createdAt"])) { $dataReal = $v; } } } } dd($dataReal);