功能打印但不能处理数组

时间:2013-01-24 12:43:37

标签: php arrays wordpress function

我们在尝试将函数生成的多个值插入到数组中时遇到了麻烦。 当我们使用字符串打印函数并手动复制结果时,它可以正常工作,但是当我们尝试使用字符串进入数组时它不起作用。

<?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 */
    ),
)
) );

?>

2 个答案:

答案 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

答案 1 :(得分: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;
} 

?>