2013-01-24 51 views
2

我們遇到了麻煩,試圖將從函數生成的多個值插入到數組中。 當我們使用一個字符串打印函數,並且我們手動複製結果時,它可以工作,但是當我們嘗試使用字符串將其轉換爲數組時,它不會。功能打印但不能工作到陣列

<?php 

function dateRange($first, $last, $step = '+1 day', $format = 'm/d/Y') { 

$current = strtotime($first); 
$last = strtotime($last); 

while($current <= $last) { 

    $dates .= "'" . date($format, $current) . "', "; 
    $current = strtotime($step, $current); 
} 

return $dates; 
} 

$all_dates = dateRange('01/20/1999', '01/23/1999'); 

echo $all_dates; /* PRINTS ALL DATES BETWEEN TWO DATES: '01/20/1999', '01/21/1999', '01/22/1999', '01/23/1999', */ 

query_posts(array(
'post_type' => 'bbdd', 
'meta_query' => array(
    $location, 
    array(
     'key' => 'date', 
     'value' => array($all_dates), /* DOESN'T WORK. INSTEAD, IF WE COPY THE RESULT OF "echo $all_dates;" MANUALLY, IT DOES WORK */ 
    ), 
) 
)); 

?> 
+0

當你做陣列($ all_dates)在你的代碼,結果不是所有日期都是單獨值的數組。結果是一個包含返回字符串的值爲ONE的數組。即不是數組('01/20/1999','01/21/1999'),而是數組(「'01/20/1999','01/21/1999'」)。 – Dragory

+0

感謝您的幫助解釋。我們現在明白了。 –

回答

3

你在函數中返回一個字符串而不是數組。

function dateRange($first, $last, $step = '+1 day', $format = 'm/d/Y') { 

    $current = strtotime($first); 
    $last = strtotime($last); 

    while($current <= $last) { 

     $dates[] = date($format, $current); 
     $current = strtotime($step, $current); 
    } 

    return $dates; 
} 

這將返回一個數組。

然後,在你的MySQL查詢:

'value' => $all_dates 
+0

它的工作。非常感謝。 –

0

爲什麼不把它放在一個數組中的首位:

<?php 

function dateRange($first, $last, $step = '+1 day', $format = 'm/d/Y') { 
    $dates = array(); 
    $current = strtotime($first); 
    $last = strtotime($last); 

    while($current <= $last) { 

      $dates[] = date($format, $current); 
      $current = strtotime($step, $current); 
    } 

    return $dates; 
} 

?>