我有一个存储在变量 $ keyword_reports_data
中的数组如下[interne] => Array
(
[Google.ca - Canada] => Array (...)
[Google.com - USA] => Array (...)
)
我有这样的代码来搜索(不完全是例如)
foreach ($keyword_reports_data['interne'] as $key => $value) {
if (array_key_exists("Google.ca", $value)) {
echo "hi " ;exit;
}
else {
echo "not exist "; exit;
}
}
但实际上它会打印
不存在
如何打印" hi"如果数组值存在,如关键字" Google.ca"只有"Google.ca" not with "Google.ca - Canada"
所以我需要为此
答案 0 :(得分:1)
数组中的键不同。将密钥从"Google.ca"
更改为"Google.ca - Canada"
。
如果您想完全匹配键,请使用array_key_exists
。
将if语句更改为:
if (array_key_exists("Google.ca - Canada", $value)) {
如果要检查密钥是否包含字符串的一部分,请使用preg_match
或strpos
。正则表达式可能很慢,因此建议使用strpos
。
以下示例:
if (preg_match('/Google.ca/', $key)) {
if (strpos($key, 'Google.ca') === 0) {
注意:我们正在使用Google.ca
检查字符串的开头是否与===
匹配。
答案 1 :(得分:1)
您需要在循环中搜索子字符串的键(而不是值)。
$data = [
'animals' => [
'UK sheep' => ['beltex', 'blackface'],
'UK pigs' => ['berkshire', 'duroc'],
'NZ sheep' => ['corriedale'],
]
];
foreach($data['animals'] as $key => $value) {
if(strpos($key,'UK') === 0) {
echo "A key found beginning with 'UK'.\n";
}
}
输出:
A key found beginning with 'UK'.
A key found beginning with 'UK'.