我有一个数组,我想在其中搜索uid并获得数组的键。
例子
假设我们有以下二维数组:
$userdb = array(
array(
'uid' => '100',
'name' => 'Sandra Shush',
'pic_square' => 'urlof100'
),
array(
'uid' => '5465',
'name' => 'Stefanie Mcmohn',
'pic_square' => 'urlof100'
),
array(
'uid' => '40489',
'name' => 'Michael',
'pic_square' => 'urlof40489'
)
);
函数调用search_by_uid(100)(第一个用户的uid)应该返回0。
函数调用search_by_uid(40489)应该返回2。
我试着做循环,但我想要一个更快的执行代码。
我修改了下面的一个例子,描述函数array_search。函数searchItemsByKey返回多维数组(N层)中通过$key返回的所有值。也许,它会对某人有用。例子:
$arr = array(
'XXX'=>array(
'YYY'=> array(
'AAA'=> array(
'keyN' =>'value1'
)
),
'ZZZ'=> array(
'BBB'=> array(
'keyN' => 'value2'
)
)
//.....
)
);
$result = searchItemsByKey($arr,'keyN');
print '<pre>';
print_r($result);
print '<pre>';
// OUTPUT
Array
(
[0] => value1
[1] => value2
)
函数代码:
function searchItemsByKey($array, $key)
{
$results = array();
if (is_array($array))
{
if (isset($array[$key]) && key($array)==$key)
$results[] = $array[$key];
foreach ($array as $sub_array)
$results = array_merge($results, searchItemsByKey($sub_array, $key));
}
return $results;
}
看起来array_filter将是合适的解决方案…
$userdb=Array
(
(0) => Array
(
(uid) => '100',
(name) => 'Sandra Shush',
(url) => 'urlof100'
),
(1) => Array
(
(uid) => '5465',
(name) => 'Stefanie Mcmohn',
(pic_square) => 'urlof100'
),
(2) => Array
(
(uid) => '40489',
(name) => 'Michael',
(pic_square) => 'urlof40489'
)
);
PHP代码
<?php
$search = 5465;
$found = array_filter($userdb,function($v,$k) use ($search){
return $v['uid'] == $search;
},ARRAY_FILTER_USE_BOTH); // With latest PHP third parameter is optional.. Available Values:- ARRAY_FILTER_USE_BOTH OR ARRAY_FILTER_USE_KEY
$values= print_r(array_values($found));
$keys = print_r(array_keys($found));
这里有一个更好的解决方案,如果您从数据库或多维数组中提取数据
多维数组的例子:
$records = array(
array(
'id' => 2135,
'first_name' => 'John',
'last_name' => 'Doe',
),
array(
'id' => 3245,
'first_name' => 'Sally',
'last_name' => 'Smith',
),
array(
'id' => 5342,
'first_name' => 'Jane',
'last_name' => 'Jones',
),
array(
'id' => 5623,
'first_name' => 'Peter',
'last_name' => 'Doe',
)
);
function search_user_by_name($name, $array) {
foreach ($array as $keys) {
foreach ($keys as $key => $_user_record) {
if ($_user_record == $name) {
return [$key => $_user_record];//Return and array of user
}
}
}
return null;
}
调用函数:
$results = search_user_by_name('John', $records);
print_r($results);
输出:Array ([first_name] => John)