如何在数组中搜索字符串?

时间:2018-11-21 00:41:05

标签: php

我在自定义字段usp-custom-60中有一个字符串:

Via Prospero Lavarello, 2, 16142 Genova GE, Italia

然后我从GET获得一个值

$myTerm = $_GET['cityName'];  

现在$myterm genova

我有一个循环,我首先尝试拆分整个字符串并将其转换为数组,然后问一个术语是否在数组中:

$catIds = array();

    while  {
        $query->the_post();
        $id = get_the_ID();
        $custom_field = usp_get_meta(false, 'usp-custom-60');
        $custom_field   = explode(" ", $custom_field);
        if (in_array($myTerm, $custom_field, true)) {
            array_push($catIds, $id);
            var_dump($catIds);
    }

但是我没有结果。如果我做var_dump($custom_field),我会得到;

array(8) { [0]=> string(3) "Via" [1]=> string(8) "Prospero" [2]=> string(10) "Lavarello," [3]=> string(2) "2," [4]=> string(5) "16142" [5]=> string(6) "Genova" [6]=> string(3) "GE," [7]=> string(6) "Italia" } array(8) { [0]=> string(3) "Via" [1]=> string(8) "Prospero" [2]=> string(10) "Lavarello," [3]=> string(2) "2," [4]=> string(5) "16142" [5]=> string(6) "Genova" [6]=> string(3) "GE," [7]=> string(6) "Italia" } array(8) { [0]=> string(3) "Via" [1]=> string(9) "Adalberto" [2]=> string(7) "Catena," [3]=> string(2) "4," [4]=> string(5) "20121" [5]=> string(6) "Milano" [6]=> string(3) "MI," [7]=> string(6) "Italia" }

根据建议的其他答案,我尝试了以下方法

$myTerm = $_GET['cityName']; 

$catIds = array();

$args = get_posts( 
    array( 
        'post_type'      => 'post', 
        'posts_per_page' => -1, 
    ) 
);
$query = new WP_Query( $args );
if ( $query->have_posts() ) {
    while ( $query->have_posts() ) {
        $query->the_post();
        $id = get_the_ID();
        $custom_field = usp_get_meta(false, 'usp-custom-60');
        if (strpos($custom_field, $myTerm) !== false) {
            array_push($catIds, $id);
        }     
        if(count($catIds) > 0){
            $arrayFUllCity = "fullCity";
        } else {
            $arrayFUllCity = "empty";
        }
    }
    //$catIds = implode( ", ", $catIds );
    var_dump($catIds);
}

但是即使array(0) { }给我3个结果,我仍然得到echo $custom_field

Via Prospero Lavarello, 2, 16142 Genova GE, Italia

Via Prospero Lavarello, 2, 16142 Genova GE, Italia

Via Adalberto Catena, 4, 20121 Milano MI, Italia

2 个答案:

答案 0 :(得分:1)

您的问题(据我所知,您在$myTerm的{​​{1}}和其中包含"genova"的字符串之间存在大小写不匹配的问题。自{{3 }}区分大小写,检查失败。我将在原始字符串上使用in_array来解决此问题,使用"Genova"检查\b周围的单词边界,然后检查{{1 }}修饰符,使正则表达式不区分大小写:

$myTerm

输出:

i

preg_match

答案 1 :(得分:0)

在这种情况下,使用strpos是最好的方法。 从我的角度来看,由于数据库关系,无法运行您的代码。但您可以尝试此解决方案。可能存在额外间距的问题。

$catIds = array();

    while  {
        $query->the_post();
        $id = get_the_ID();
        $custom_field = usp_get_meta(false, 'usp-custom-60');
        $custom_field = explode(" ", $custom_field);
        $custom_field = array_map('trim', $custom_field);
        if (in_array($myTerm, $custom_field, true)) {
            array_push($catIds, $id);
            var_dump($catIds);
    }