我有一个数组,我想在其中搜索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)

/**
 * searches a simple as well as multi dimension array
 * @param type $needle
 * @param type $haystack
 * @return boolean
 */
public static function in_array_multi($needle, $haystack){
    $needle = trim($needle);
    if(!is_array($haystack))
        return False;

    foreach($haystack as $key=>$value){
        if(is_array($value)){
            if(self::in_array_multi($needle, $value))
                return True;
            else
               self::in_array_multi($needle, $value);
        }
        else
        if(trim($value) === trim($needle)){//visibility fix//
            error_log("$value === $needle setting visibility to 1 hidden");
            return True;
        }
    }

    return False;
}

你可以结合使用两个函数,array_search和array_column。

$search_value = '5465';
$search_key   = 'uid';
$user = array_search($search_value, array_column($userdb, $search_key));

print_r($userdb[$user]);

5465是要搜索的用户ID, uid是包含用户ID的键,$userdb是问题中定义的数组。

引用:

php。net上的Array_search

net上的Array_column

我必须使用un函数来查找数组中的每个元素。所以我修改了Jakub truneeek的函数如下:

function search_in_array_r($needle, $array) {
    $found = array();
    foreach ($array as $key => $val) {
        if ($val[1] == $needle) {
            array_push($found, $val[1]);
        }
    }
    if (count($found) != 0)
        return $found;
    else
        return null;
}