skip to Main Content

I want to get closest date from $search_date if is not same values in $array[‘date’]. If is same value in $array[‘date’] I want all array.

  • Format date is ‘Y-m-d’.

Example 1:

$search_date = '2022-12-08';
$array = [{"price":"200","date":"2022-12-12"},{"price":"50","date":"2022-12-10"},{"price":"100","date":"2022-12-10"}]
Return should be: [{"price":"50","date":"2022-12-10"},{"price":"100","date":"2022-12-10"}]

Example 2:

$search_date = '2022-12-08';
$array = [{"price":"200","date":"2022-12-08"},{"price":"50","date":"2022-12-09"},{"price":"100","date":"2022-12-11"}]
Return should be: [{"price":"200","date":"2022-12-08"}]

Example 3:

$search_date = '2022-12-08';
$array = [{"price":"200","date":"2022-12-10"},{"price":"100","date":"2022-12-10"},{"price":"50","date":"2022-12-11"}]
Return should be: [{"price":"200","date":"2022-12-10"},{"price":"100","date":"2022-12-10"}]

Example 4:

$search_date = '2022-12-08';
$array = [{"price":"200","date":"2022-12-08"},{"price":"100","date":"2022-12-08"},{"price":"50","date":"2022-12-08"}]
Return should be: [{"price":"200","date":"2022-12-08"},{"price":"100","date":"2022-12-08"},{"price":"50","date":"2022-12-08"}]

Thank you!

3

Answers


  1. If you want to search for a specific value in your array have you tried

    array_search($value, $array); 
    

    By this you can search for a specific value in your array


    If you want to search the lowest value

    try to for looping your array and check if the array is lower than the previous index and if the for loop has ended you have the lowest date

    $lowest_date = null;
    
    for ($i = 0; count($i); $i++) {
        if ($array['date'] < $lowest_date) {
            $lowest_date = $array['date'];
        }
    }
    
    Login or Signup to reply.
  2. This code calculates the distance in days between $search and each record. It assumes that you want to find closest distance in both future and past.

    <?php
    
    /*
    
    Question Author: Catalin Iamandei
    Question Answerer: Jacob Mulquin
    Question: PHP - get closest date from array
    URL: https://stackoverflow.com/questions/74598442/php-get-closest-date-from-array
    Tags: php, arrays, laravel, date, php-carbon
    
    */
    
    $search = '2022-12-10';
    $searchObj = new DateTime($search);
    
    $records = json_decode('[{"price":"200","date":"2022-12-10"},{"price":"100","date":"2022-12-10"},{"price":"50","date":"2022-12-11"}]', true);
    
    $distances = [];
    foreach ($records as $index => $record) {
        $recordObj = new DateTime($record['date']);
        $daysDiff = $searchObj->diff($recordObj)->format("%r%a");
        $distances[$index] = abs($daysDiff);
    }
    
    $minimumDiff = min($distances);
    
    $output = [];
    foreach ($distances as $index => $distance) {
        if ($distance == $minimumDiff) {
            $output[] = $records[$index];
        }
    }
    
    echo json_encode($output, JSON_PRETTY_PRINT);
    

    Yields:

    [
        {
            "price": "50",
            "date": "2022-12-09"
        },
        {
            "price": "100",
            "date": "2022-12-11"
        }
    ]
    

    If you only want to search for closest dates in the future, you need to remove the abs() function and then remove all negative entries in the $distances array before using min().

    Login or Signup to reply.
  3. you dont have mentioned what todo with prior dates, eg. searching for '2022-12-07', how to tread 2022-12-06 and 2022-12-08, as the difference both is 1. You can calculate the datediff for each entry, get the min datediff and output elements with this datediff. eg :

    <?php
    $SearchDate = new DateTimeImmutable('2022-12-08');
    $array      = array ('{"price":"200","date":"2022-12-12"}',
        '{"price":"50","date":"2022-12-10"}',
        '{"price":"100","date":"2022-12-10"}');
    $laResult = array();
    foreach($array as $jsonO) {
        $json             = json_decode($jsonO);
        $CompareDate      = new DateTimeImmutable($json->{'date'});
        $interval         = date_diff($SearchDate, $CompareDate);
        $laThis['date']   = $json->{'date'};
        $laThis['diff']   = $interval->format('%a');
        $laThis['origin'] = $jsonO;
        $laResult[]       = $laThis;
    }
    
    $min_diff = min( array_column( $laResult, 'diff') );
    echo 'nearestDiff:'. $min_diff .PHP_EOL;
    foreach($laResult as $laSingleResult) {
        if($laSingleResult['diff'] == $min_diff) {
            echo $laSingleResult['origin'] .PHP_EOL;
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search