Home > Net >  Get results with latest date in foreach loop in php?
Get results with latest date in foreach loop in php?

Time:09-28

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'

CodePudding user response:

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);

CodePudding user response:

You need to sort by date to determine which is the latest data.

$dataReal = '';
foreach ($data as $v) {
   if($v['order'] == 3) {
     // Assign value only when $dataReal is empty or createAt is newer than the previous result
     if (empty($dataReal) || $v['createAt '] > $dataReal['createAt ']) {
         $dataReal = $v;
     }
  } 
}

CodePudding user response:

You need to compare the createdAt timestamp in your loop:

$dataReal = null;
foreach ($data as $v) {
    if(
        $v['order'] == 3 && // check for order
        (
            $dataReal === null || // dataReal is empty
            strtotime($dataReal['createdAt']) < strtotime($v['createdAt']) // override if date is newer
            
        )
    ) {
        $dataReal = $v;
    } 
}

Working example: https://3v4l.org/p6gnq

  •  Tags:  
  • php
  • Related