如何使用php在数组中搜索
我试图为我的网站做一个搜索功能,但我无法让它工作。 这是我的密码:如何使用php在数组中搜索,php,arrays,Php,Arrays,我试图为我的网站做一个搜索功能,但我无法让它工作。 这是我的密码: $search_string = "html documentation"; $search_string = explode(' ', $search_string); $array = " Array ( [0] => Array ( [0] => 404 [1] => notfound [2] => error ) [1] =&
$search_string = "html documentation";
$search_string = explode(' ', $search_string);
$array = "
Array (
[0] => Array (
[0] => 404
[1] => notfound
[2] => error
)
[1] => Array (
[0] => 403
[1] => forbidden
[2] => error
)
[2] => Array (
[0] => home
)
[3] => Array (
[0] => hcjp
[1] => html
[2] => css
[3] => js
[4] => php
[5] => learning
[6] => documentation
)
[4] => Array (
[0] => about
)
[5] => Array (
[0] => search
[1] => search on no conditions
)
[6] => Array (
[0] => search
[1] => search on label
)
)
";
$search_result = in_array($search_string, $array);
print_r($search_result);
我没有得到任何输出,我的目标是得到某种路径,如:[3],以便我知道:
$search_result[3]
包含用户请求的信息
谢谢一种方法可能是在
$array
中循环数组并使用。如果存在匹配项,则从$array
foreach ($array as $key => $a) {
if (count(array_intersect($a, $search_string)) > 0) {
echo $key;
}
}
您编写的代码有一些问题 该函数返回一个字符串数组,即使数组中的
可以支持作为指针的数组,但您构建$array
的方式即使不是不可能,也会让它变得非常困难。另外,您的$array
是一个数组数组,而不是一维数组
下面的解决方案可以满足您的需要,但请记住,如果您的$array
包含数百个子数组,那么它将不是最有效的解决方案
// get search term
$search_string = "html documentation";
// explode in on space => ['html', 'documentation']
$search_strings = explode(' ', $search_string);
$array = [
['404', 'not found', 'error'],
['403', 'forbidden', 'error'],
['home'],
['hcop', 'html', 'css', 'js', 'php', 'learning', 'documentation'],
...
];
// set an array that will hold your search related info
$search_result = [];
// go through the search terms i.e. html, documentation
foreach($search_strings as $term) {
// loop through your array, $key will be the index of the sub-array and $value the sub-array itself
foreach($array as $key => $value) {
// if the term is in the sub-array, set the $term as key and the $key as the value
if (in_array($term, $value)) {
$search_result[$term] = $key;
}
}
}
// Array ( [html] => 3 [documentation] => 3 )
print_r($search_result);
您可以使用preg_grep,查看匹配的计数是否与输入字计数相同
$search_string = "html documentation";
$searchArr = explode(" ", $search_string);
$search_strings = "/" . implode('|', $searchArr) ."/";
$array = [
['404', 'not found', 'error'],
['403', 'forbidden', 'error'],
['home'],
['hcop', 'html', 'css', 'js', 'php', 'learning', 'documentation']
];
foreach($array as $key => $arr){
$out = preg_grep($search_strings, $arr);
if(count($out) == count($searchArr)){
echo "match in key $key!\n";
var_dump($arr);
}
}