0

I try to match to arrays based on the dates. The first array is generated by a function (getDateRange), the second array comes from my Wordpress database.

function getDateRange($startDate, $endDate, $format="Y-m-d")
    {
        //Create output variable
        $datesArray = array();
        //Calculate number of days in the range
        $total_days = round(abs(strtotime($endDate) - strtotime($startDate)) / 86400, 0) + 1;
        if($total_days<0) { return false; }
        //Populate array of weekdays and counts
        for($day=0; $day<$total_days; $day++)
        {
            $datesArray[] = date($format, strtotime("{$startDate} + {$day} days"));
        }
        //Return results array
        return $datesArray;
    }


$sql = "SELECT date(datetime) AS date, SUM(amount) as amount FROM sales GROUP BY 1";
$results = $wpdb->get_results($sql, ARRAY_A);

// Generate the date range 
$dateRange = getDateRange('2014-10-01', '2014-10-06');

foreach($dateRange as $date) {
 echo $date . ' | ';

    if (array_key_exists($date, $results)) {
    echo 'OK';

    } else {
     echo '0';   
    }
    echo '<br />';
}

With the code above I don't get matching values:

2014-10-01 | 0
2014-10-02 | 0
2014-10-03 | 0
2014-10-04 | 0
2014-10-05 | 0
2014-10-06 | 0

The desired result is:

2014-10-01 | 0
2014-10-02 | 0
2014-10-03 | OK
2014-10-04 | 0
2014-10-05 | OK
2014-10-06 | 0
Citizen SP
  • 1,411
  • 7
  • 36
  • 68

2 Answers2

1

ARRAY_A - result will be output as an numerically indexed array of associative arrays, using column names as keys

From the Codex

So array_key_exists will search the date in the keys of $results array, which has only numeric keys.

You could implement a search function for multidimensional arrays instead of array_key_exists

function searchForDate($date, $array) {
    foreach ($array as $key => $val) {
        if ($val['date'] === $date) {
            return $key;
        }
    }
    return null;
}

modified from: PHP multidimensional array search by value

Community
  • 1
  • 1
patman
  • 2,780
  • 4
  • 30
  • 54
0

First of all, the right answer relies on how does your $results array looks like...

 Array ( [0] => 2014-10-01 [1] => 2014-10-02 [2] => 2014-10-03 [3] => 2014-10-04 [4] => 2014-10-05 [5] => 2014-10-06 )

that, is your $dateRange array. Normally, upon foreach, you will get each date as a simple string, so, in turn, your $date var will be:
2014-10-01
2014-10-02
2014-10-03
2014-10-04
2014-10-05
2014-10-06

And those are the values used in if (array_key_exists($date, $results)) {}. This means, that, using this scenario, your $results array must have dates as keys, so it should look something like:
Array ( [2014-10-03] => 'foo' [2014-10-06] => 'bar' )

After this, you will definitely have hits. But again, without a dump of $results I cannot guarantee that this is what you need.

Hope it helps!
Keep on coding!
Ares.

Ares Draguna
  • 1,641
  • 2
  • 16
  • 32