2

I have this array:

array(2) { 
    [0]=> array(2) {
        ["url"]=> string(104) "aHR0cDovL3lvdXR1YmUuY29t"
        ["date"]=> string(19) "2014-01-06 21:44:39" 
     }

    [1]=> array(2) { 
        ["url"]=> string(28) "aHR0cDovL3d3dy5nb29nbGUuY29t"
        ["date"]=> string(19) "2014-01-06 14:28:32"
     }
 } 

How can I parse the $row['date'] for the earliest date?

4
  • Well, you can sort it and then get the first/last element Commented Jan 6, 2014 at 20:31
  • possible duplicate of How to find the maximum and minimum date by key Commented Jan 6, 2014 at 20:32
  • Are you getting this array from a database? You can change up the query (ORDER BY date ASC if you're in MySQL) to automatically give you sorted results, oldest date first. Commented Jan 6, 2014 at 20:33
  • @Esaevian Nop it is not from a database Commented Jan 6, 2014 at 20:47

3 Answers 3

9

I think you can do this using array_map and min functions:

function customFunction($array) {
  return $array['date'];
}
$dateArray= array_map('customFunction', $array);

So, you have an array with your dates, after just do:

$oldDate = min($dateArray); //here you get the oldest date
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you. This work perfectly. Is it possible I can make minus 1 second from the $oldate?
Yes, look here: stackoverflow.com/questions/12885098/…, hope it help you
@jQuerybeast I think DateTime::sub should do the trick.
5

To find the min date in array try this code

 $minDate = min(array_map(function($item) { return $item['date']; }, $array));

3 Comments

How can I make this minus 1 second?
echo date("Y-m-d H:i:s", strtotime($minDate) - 1)
If nulls are messing up your min(), see stackoverflow.com/a/23565246/470749
1

Something simple like this should do

$earliest_date = date_create();
foreach($rows as $row) {
    $date = date_create($row['date']);
    if($date < $earliest_date)
        $earliest_date = $date;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.