gpt4 book ai didi

php - 如何防止我的函数将 "0"视为空?

转载 作者:行者123 更新时间:2023-12-05 04:35:28 26 4
gpt4 key购买 nike

我有一个彩票搜索表单,它将六个输入字段连接成一个值,并根据位置返回彩票结果。我的表单适用于数字 1-9,但当我搜索 0 时无法显示结果。

我相信这是因为在我的 get_numbers() 函数中,“0”的值被视为空值:https://www.php.net/manual/en/function.empty.php

如何修复我的 if else 语句以阻止它将 0 视为空?

    add_filter('wp_ajax_nopriv_get_numbers', 'get_numbers', 10);
add_filter('wp_ajax_get_numbers', 'get_numbers', 10);

function get_numbers(){
$str = '';
if(!empty($_POST['n_1'])){
$str .= $_POST['n_1'];
}else{
$str .= '.';
}
if(!empty($_POST['n_2'])){
$str .= $_POST['n_2'];
}else{
$str .= '.';
}
if(!empty($_POST['n_3'])){
$str .= $_POST['n_3'];
}else{
$str .= '.';
}
if(!empty($_POST['n_4'])){
$str .= $_POST['n_4'];
}else{
$str .= '.';
}
if(!empty($_POST['n_5'])){
$str .= $_POST['n_5'];
}else{
$str .= '.';
}
if(!empty($_POST['n_6'])){
$str .= $_POST['n_6'];
}else{
$str .= '.';
}

$atts = array(
'numberposts' => -1,
'posts_per_page' => -1,
'post_type' => 'product',
'meta_query' => array(
array(
'key' => 'product_overlay_text',
'value' => $str,
'compare' => 'REGEXP',
),
),
);
$the_query = new WP_Query( $atts );

ob_start();
if($the_query->have_posts()) :
woocommerce_product_loop_start();
while($the_query->have_posts()) : $the_query->the_post();
wc_get_template_part( 'content', 'product' );
endwhile;
woocommerce_product_loop_end();
$content['tickets_data'] = ob_get_clean();
else:
$content['tickets_data'] = 'เลขที่ท่านต้องการไม่มีในแผง';
endif;

最佳答案

你是正确的,empty()0 返回 TRUE

您可以改为使用 filter_input()应用了 FILTER_VALIDATE_INT 过滤器。

您甚至可以使用范围图简化整个事情...

$str = implode("", array_map(function($i) {
$val = filter_input(
INPUT_POST,
"n_$i",
FILTER_VALIDATE_INT
);

return $val === null || $val === false
? '.'
: $val;
}, range(1, 6)));

关于php - 如何防止我的函数将 "0"视为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71028593/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com