我想在多维数组中搜索特定字符串的所有键。我只需要解决它的现状,仅此而已。我想知道任何数组中是否存在访问者的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
)
)
由于
答案 0 :(得分:1)
我可以想象一种你不必循环的方式(至少你自己):
$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,
),
);
它正确返回值21
的键(22
,23
和109.148.183.1
):
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
)
)
答案 1 :(得分:0)
永远无法避免循环: - )
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*/}
答案 2 :(得分:0)
$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');
或者,您可以编写自己的递归函数并避免使用全局函数。这只是最直接的方式。