phparraysmultidimensional-arraymindate-comparison

Get earliest Y-m-d date value in a multidimensional array from qualifying rows


I want to get the minimum date from the date column of a multidimensional array, but only from rows with keycode of 0001.

How would I achieve that?

$a = [
  "a" => ['keycode' => '0001','date' => "2015-09-08"],
  "b" => ['keycode' => '0002','date' => "2015-09-05"],
  "c" => ['keycode' => '0003','date' => "2015-09-04"],
  "d" => ['keycode' => '0001','date' => "2015-09-01"],
  "e" => ['keycode' => '0001','date' => "2015-08-01"]
];

Expected result: 2015-08-01


Solution

  • I would first extract all of the values that have a keycode of 0001 and create a new array of just those dates. Then use the php min() function.

    PHP Fiddle

    $a=array(
      "a" => array('keycode' => '0001','date' =>"2015-09-08"),
      "b" => array('keycode' => '0002','date' =>"2015-09-05"),
      "c" => array('keycode' => '0003','date' =>"2015-09-04"),
      "d" => array('keycode' => '0001','date' =>"2015-09-01"),
      "e" => array('keycode' => '0001','date' =>"2015-08-01")
    );
    
    $b = [];
    
    foreach($a as $key => $value){
        if($value['keycode']=='0001'){
         $b[]=$value['date'];
        }
    }
    
    print_r($b);
    
    echo min($b);