简体   繁体   English

在PHP数组中搜索子字符串

[英]Search substring in a PHP Array

I am trying to find a particular string in a PHP array as below. 我试图在如下所示的PHP数组中找到特定的字符串。

Array ( [0] => Array ( [0] => sku,qty,is_in_stock ) [1] => Array ( [0] => EBCDAA014MAS34B,149.000000,1 ));

I am preparing the above array as below and I am storing it in a variable called $listing 我正在如下准备上面的数组,并将其存储在名为$listing的变量中

And I am using array_find() function to do so. 我正在使用array_find()函数来做到这一点。

function array_find($needle, array $haystack)
{
    foreach ($haystack as $key => $value) {
        if (false !== stripos($value, $needle)) {
            return $key;
        }
    }
    return false;
}

$hello = array_find('EBCDAA014MAS34B', $listing);
echo $hello;

But still, I am getting the return as false. 但仍然,我得到的回报是虚假的。 Can anyone kindly tell me which is the right way to do this? 有人可以告诉我哪种方法是正确的吗?

Your array is an array of arrays where your string is the first item in each of those arrays which will be $value[0] 您的数组是一个数组数组,其中字符串是每个数组中的第一项,其$value[0]

Try changing this line: 尝试更改此行:

if (false !== stripos($value, $needle)) {

To this line: 到这行:

if (false !== stripos($value[0], $needle)) {

Demo 演示版

Simply you can use in_array() PHP Function, see below example. 只需使用in_array() PHP函数,请参见以下示例。

    $listing = Array ( [0] => Array ( [0] => sku,qty,is_in_stock ) [1] => Array ( [0] => EBCDAA014MAS34B,149.000000,1 ));
in_array('EBCDAA014MAS34B', $listing)

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

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