2013-01-24 50 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; 
} 

?>