简体   繁体   English

如何检查数组是否包含子字符串 php

[英]How to check if array contains a substring php

I have an array of arrays as such below and I want to check if the [avs_id] contains a substring "a_b_c".我有一个如下所示的数组数组,我想检查 [avs_id] 是否包含子字符串“a_b_c”。 How to do this in php?如何在 php 中做到这一点?

  Array
            (
                [id] => 10003    
                [avs_id] => a_b_c_3248
            )

    Array
        (
            [id] => 10003    
            [avs_id] => d_e_f_3248
        )

You can use array_filter() :您可以使用array_filter()

$src = 'a_b_c';

$result = array_filter
(
    $array,
    function( $row ) use( $src )
    {
        return (strpos( $row['avs_id'], $src ) !== False);
    }
);     

eval.in demo eval.in 演示

The result maintain original keys, so you can directly retrieve item(s) matching substring.结果保持原始键,因此您可以直接检索匹配子字符串的项目。

If you want only check if substring exists, or the number of items having substring, use this:如果您只想检查子字符串是否存在,或具有子字符串的项目数,请使用以下命令:

$totalMatches = count( $result );

Loop through your array and test for the string in the specific element of your array with strpos as in the example code below.循环遍历数组并使用 strpos 测试数组特定元素中的字符串,如下面的示例代码所示。

foreach($yourMainArray as $arrayItem){
    if (strpos($arrayItem['avs_id'], 'a_b_c') !== false) {
        echo 'true';
    }
}

A loop may be more ideal but if you know what array index the string is in that you are after:循环可能更理想,但如果您知道字符串所在的数组索引,您将在:

$arr = array('id'=>'10003', 'avs_id'=>'a_b_c_3248');

if (strpos($arr['avs_id'], 'a_b_c') !== false) {
    echo 'string is in avs_id';
}

You can use :您可以使用 :

foreach($yourArray as $arrayItem){
    if (strpos($arrayItem['avs_id'], 'a_b_c') !== false) {
        //return true : code here
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM