我想在多维数组中的所有键中搜索特定字符串。我只需要弄清楚它是否存在,仅此而已。我想知道访问者的IP是否存在于任何阵列中。
有没有php函数或方法可以用来实现这一点,我尝试过的每一个都会返回false。(in_array,array_search,array_filter(
我希望避免循环遍历每个键和一组值。
示例阵列
Array
(
[21] => Array
(
[click_id] => 21
[ip_addr] => 109.148.183.1
[dtime] => 2011-04-28 17:56:57
[url_id] => 11
)
[22] => Array
(
[click_id] => 22
[ip_addr] => 109.148.183.1
[dtime] => 2011-04-28 17:57:05
[url_id] => 12
)
[23] => Array
(
[click_id] => 23
[ip_addr] => 109.148.183.1
[dtime] => 2011-04-28 18:42:42
[url_id] => 10
)
)
感谢
我可以想象一种你不必循环(至少你自己(的方法:
$term = preg_quote('109.148.183.1', '~'); // lets make sure it's safe
$result = array_map('unserialize', preg_filter('~' . $term . '~', '$0', array_map('serialize', $data)));
echo '<pre>';
print_r($result);
echo '</pre>';
使用您的示例数据:
$data = array
(
21 => array
(
'click_id' => 21,
'ip_addr' => '109.148.183.1',
'dtime' => '2011-04-28 17:56:57',
'url_id' => 11,
),
22 => array
(
'click_id' => 22,
'ip_addr' => '109.148.183.1',
'dtime' => '2011-04-28 17:57:05',
'url_id' => 12,
),
23 => array
(
'click_id' => 23,
'ip_addr' => '109.148.183.1',
'dtime' => '2011-04-28 18:42:42',
'url_id' => 10,
),
);
它正确地返回值为109.148.183.1
:的密钥(21
、22
和23
(
Array
(
[21] => Array
(
[click_id] => 21
[ip_addr] => 109.148.183.1
[dtime] => 2011-04-28 17:56:57
[url_id] => 11
)
[22] => Array
(
[click_id] => 22
[ip_addr] => 109.148.183.1
[dtime] => 2011-04-28 17:57:05
[url_id] => 12
)
[23] => Array
(
[click_id] => 23
[ip_addr] => 109.148.183.1
[dtime] => 2011-04-28 18:42:42
[url_id] => 10
)
)
由于这是一个正则表达式,我们可以进行更强大的搜索,例如搜索所有具有奇数秒数的2011-04-28
日期:
$term = '2011-04-28 [0-9]{2}:[0-9]{2}:[0-9][13579]';
$result = array_map('unserialize', preg_filter('~' . $term . '~', '$0', array_map('serialize', $data)));
echo '<pre>';
print_r($result);
echo '</pre>';
输出:
Array
(
[21] => Array
(
[click_id] => 21
[ip_addr] => 109.148.183.1
[dtime] => 2011-04-28 17:56:57
[url_id] => 11
)
[22] => Array
(
[click_id] => 22
[ip_addr] => 109.148.183.1
[dtime] => 2011-04-28 17:57:05
[url_id] => 12
)
)
永远无法避免循环:-(
function search($array, $searchString){
foreach($array as $key=>$val){
if(in_array($searchString, $val)) return true;
}
return false;
}
//use it like so:
if(search($array, '109.148.183.1')){/*do something*/}
$matching_keys = array();
function search ($item, $key) {
global $matching_keys();
// do your testing here, stuff matches in $matching_keys, or however you wanna do it
}
array_walk_recursive($array, 'search');
或者,您可以编写自己的递归函数,避免使用全局函数。这只是最直接的方式。