【问题标题】:Function printing but not working into an array功能打印但不能进入数组
【发布时间】:2013-01-08 05:28:35
【问题描述】:

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

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

?>

【问题讨论】:

  • 当您在代码中执行 array($all_dates) 时,结果不是一个将所有日期作为单独值的数组。结果是一个包含返回字符串的值为 ONE 的数组。即,不是 array('01/20/1999', '01/21/1999') 而是 array("'01/20/1999', '01/21/1999'")。
  • 感谢您的帮助解释。我们现在明白了。

标签: php arrays wordpress function


【解决方案1】:

为什么不把它放在一个数组中:

<?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;
} 

?>

【讨论】:

    【解决方案2】:

    您在函数中返回的是字符串,而不是数组。

    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
    

    【讨论】:

      猜你喜欢
      • 2022-01-01
      • 2018-07-10
      • 1970-01-01
      • 1970-01-01
      • 2014-11-29
      • 2013-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多