从php中的数组中获取匹配值和密钥
问题描述:
如何从php中的数组中获取匹配值。 例子:从php中的数组中获取匹配值和密钥
<?php
$a=array("1"=>"Hello","2"=>"World","3"=>"Check","4"=>"Here");
?>
从$一个,如果我有像"He"
或"ld"
或"che"
,如何显示基于文本得到匹配值和数组中的键文本。就像查询一样的SQL。
答
这是简单的一个班轮。
您可能正在寻找preg_grep()
。使用此功能,您可以从给定的阵列中找到可能的REGEX
。
$a=array("1"=>"Hello","2"=>"World","3"=>"Check","4"=>"Here");
$matches = preg_grep ("/^(.*)He(.*)$/", $a);
print_r($matches);
答
可以遍历数组,检查每一个值,如果它包含搜索字符串:
$searchStr = 'He';
$a=array("1"=>"Hello","2"=>"World","3"=>"Check","4"=>"Here");
foreach($a as $currKey => $currValue){
if (strpos($currValue, $searchStr) !== false) {
echo $currKey.' => '. $currValue.' ';
}
}
//prints 1 => Hello 4 => Here
答
你可以为创造功能,像这样:
function find_in_list($a, $find) {
$result = array();
foreach ($a as $el) {
if (strpos($el, $find) !== false) {
$result[] = $el;
};
}
return $result;
}
这里是你如何可以调用它:
print_r (find_in_list(array("Hello","World","Check","Here"), "el"));
输出:
Array ([0] => Hello)
请您详细说明您正在尝试做什么?我不完全确定你想做什么。 你是否试图在数组中存在“他”? – uruloke