2014-10-22 121 views
0

我嘗試根據日期匹配數組。第一個數組由函數(getDateRange)生成,第二個數組來自我的Wordpress數據庫。根據日期匹配兩個數組

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 />'; 
} 

利用上述我的代碼沒有得到匹配值:

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

期望的結果是:

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

var_dump($ results)'返回什麼? – rnevius 2014-10-22 08:45:45

回答

1

ARRAY_A - 結果將是作爲數字索引輸出使用列名作爲鍵的關聯陣列陣列

Codex

所以array_key_exists將搜索在$results陣列,它只有數字鍵的鍵日期。

您可以實現搜索功能的多維數組,而不是array_key_exists

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

從修改:PHP multidimensional array search by value

0

首先,正確的答案依賴於請問你的$results陣列看起來像...

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) 

那,你的$dateRange數組。通常情況下,在的foreach,你會得到每一個日期作爲簡單的字符串,那麼,反過來,你的$date VAR將是:
2014-10-01
2014年10月2日
2014年10月3日
2014 -10-04
2014年10月5日
2014年10月6日

和那些在if (array_key_exists($date, $results)) {}使用的值。這意味着,採用這種情況下,您的$results陣列必須有日期作爲鍵,所以它應該是這個樣子:
Array ([2014-10-03] => 'foo' [2014-10-06] => 'bar')

在此之後,你一定有命中。 但是,沒有$results轉儲,我不能保證這是你所需要的。

希望它能幫助!
繼續編碼!戰神。