php 通过任意列中的值不区分大小写地过滤2D数组[重复]

ma8fv8wu  于 5个月前  发布在  PHP
关注(0)|答案(1)|浏览(60)

此问题在此处已有答案

Filter a 2d array to keep rows with a value in any column which case-insensitively matches a search substring(2个答案)
8天前关闭
我想通过一个搜索词来过滤(搜索)一个多维数组。我不想让搜索词与键或值严格一致,而更像是一个不区分大小写的包含。
JSON中的数据如下所示:

[
    {"title":"The Call of the Wild","author":"Jack London"},
    {"title":"Great Expectations","author":"Charles Dickens"},
    {"title":"The Voyage of the Beatle","author":"Charles Darwin"}
]

字符串
我希望能够能够返回一个数组的结果的基础上的搜索。例如,对查尔斯一词的搜索应该拉了第二个两个标题,而对野生搜索应该返回第一个标题。
我一直在尝试修改下面的和answers here,但它似乎只是给予我数组的索引。我如何搜索数组中所有元素的标题和作者的值?

function searchArrayKeyVal($sKey, $search, $array) {
    foreach ($array as $key => $val) {
        if (strpos(strtolower($val[$sKey]), strtolower(trim($search))) !== false) {
            return $key;
        }
    }
         return false;
 }


仅供参考,有一个旧版本的PHP(5.3)我不能在我的客户端主机上更改,所以我不能使用新的方法。

pdsfdshx

pdsfdshx1#

假设你已经将JSON解码为数组,你可以使用这个函数来搜索。它会遍历数组的每个条目,使用stripos搜索每个值以进行不区分大小写的搜索。任何匹配的条目都会被推送到$results数组中,该数组在函数结束时返回:

function searchArrayKeyVal($search, $array) {
    $results = array();
    // search for string in each column
    foreach ($array as $idx => $obj) {
        foreach ($obj as $key => $value) {
            if (stripos($value, $search) !== false) {
                array_push($results, $obj);
                break;
            }
        }
    }
    return $results;
}

print_r(searchArrayKeyVal('charles', $array));
print_r(searchArrayKeyVal('wild', $array));

字符串
输出量:

Array
(
    [0] => Array
        (
            [title] => Great Expectations
            [author] => Charles Dickens
        )
    [1] => Array
        (
            [title] => The Voyage of the Beatle
            [author] => Charles Darwin
        )
)

Array
(
    [0] => Array
        (
            [title] => The Call of the Wild
            [author] => Jack London
        )
)


Demo on 3v4l.org

相关问题