PHP多维数组按值搜索

Rac*_*hit 298 php arrays multidimensional-array

我有一个数组,我想搜索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'
    )
);
Run Code Online (Sandbox Code Playgroud)

函数调用search_by_uid(100)(第一个用户的uid)应该返回0.

函数调用search_by_uid(40489)应该返回2.

我尝试制作循环,但我想要更快的执行代码.

Jak*_*ček 428

function searchForId($id, $array) {
   foreach ($array as $key => $val) {
       if ($val['uid'] === $id) {
           return $key;
       }
   }
   return null;
}
Run Code Online (Sandbox Code Playgroud)

这会奏效.你应该这样称呼它:

$id = searchForId('100', $userdb);
Run Code Online (Sandbox Code Playgroud)

重要的是要知道,如果你使用的是很重要的===运营商相比,类型必须完全相同,在这个例子中,你必须寻找string或只是使用==代替===.

基于angoru的回答.在PHP(>= 5.5.0)的更高版本中,您可以使用单行程.

$key = array_search('100', array_column($userdb, 'uid'));
Run Code Online (Sandbox Code Playgroud)

这是文档:http://php.net/manual/en/function.array-column.php.

  • 请记住,如果您的数组键不是 _0, 1, 2, 3, n_ (数字且按从零开始的顺序),单行答案将不起作用,因为使用 `array_column` 将重置键。 (8认同)
  • 您还应该能够使用array_map代替array_column,在没有PHP 5.5的情况下执行此操作.只需将`array_column($ userdb,'uid')`替换为`array_map(function($ v){return $ v ['uid'];},$ userdb)` (4认同)
  • 是的,你是对的。Lambda 函数自 PHP 5.3 起可用。更好的是 `array_search`,不是吗? (2认同)
  • @angoru 我认为原始解决方案(`foreach` 循环)的执行速度会更快,因为它会在找到匹配项后立即停止。较新的解决方案必须遍历整个数组一次以提取“array_column”,然后第二次循环遍历它以执行搜索(直到找到匹配项)。较新的解决方案更易于阅读、更简洁,但 OP 专门提出了性能问题 (2认同)

ang*_*oru 285

如果您正在使用(PHP 5> = 5.5.0),则不必编写自己的函数来执行此操作,只需编写此行即可完成.

如果你只想要一个结果:

$key = array_search(40489, array_column($userdb, 'uid'));
Run Code Online (Sandbox Code Playgroud)

对于多个结果

$keys = array_keys(array_column($userdb, 'uid'), 40489);
Run Code Online (Sandbox Code Playgroud)

如果您在注释中指定了一个关联数组,您可以使用它:

$keys = array_keys(array_combine(array_keys($userdb), array_column($userdb, 'uid')),40489);
Run Code Online (Sandbox Code Playgroud)

如果您使用PHP <5.5.0,则可以使用此backport,谢谢ramsey!

更新:我一直在制作一些简单的基准测试,多种结果形式似乎是最快的,甚至比Jakub定制功能更快!

  • 我编辑帖子以包含多个结果. (3认同)
  • 当 $userdb 中的键没有以 0,1,2 等开头时,这对我不起作用,并说键是 1234,4566 等。array_search 之后的结果键总是 0,1,2 等等在 (3认同)
  • 这不适用于关联数组,但是您可以像这样解决这个问题:`array_search(40489, array_combine(array_keys($userdb), array_column($userdb, 'uid')))` (3认同)

ref*_*xiv 25

建立Jakub的优秀答案,这是一个更通用的搜索,它将允许指定密钥(不仅仅是uid):

function searcharray($value, $key, $array) {
   foreach ($array as $k => $val) {
       if ($val[$key] == $value) {
           return $k;
       }
   }
   return null;
}
Run Code Online (Sandbox Code Playgroud)

用法: $results = searcharray('searchvalue', searchkey, $array);


小智 24

在PHP的后续版本(> = 5.5.0)中,您可以使用这个单行程序:

$key = array_search('100', array_column($userdb, 'uid'));
Run Code Online (Sandbox Code Playgroud)

  • 只需将 array_column 结果放入特定变量中,避免为数组上的每个结果调用 array_column 。 (5认同)

amu*_*ell 19

我知道这已经得到了解答,但是我使用了这个并在代码中扩展了一些,所以你没有只用uid进行搜索.我只是想为其他可能需要该功能的人分享它.

这是我的例子,请记住这是我的第一个答案.我拿出了param数组,因为我只需要搜索一个特定的数组,但你可以很容易地将它添加进去.我想要的不仅仅是搜索uid.

此外,在我的情况下,由于可能不是唯一的其他字段搜索,可能会有多个键返回.

 /**
     * @param array multidimensional 
     * @param string value to search for, ie a specific field name like name_first
     * @param string associative key to find it in, ie field_name
     * 
     * @return array keys.
     */
     function search_revisions($dataArray, $search_value, $key_to_search) {
        // This function will search the revisions for a certain value
        // related to the associative key you are looking for.
        $keys = array();
        foreach ($dataArray as $key => $cur_value) {
            if ($cur_value[$key_to_search] == $search_value) {
                $keys[] = $key;
            }
        }
        return $keys;
    }
Run Code Online (Sandbox Code Playgroud)

后来,我最终编写了这个,以便我可以搜索另一个值和关联键.因此,我的第一个示例允许您在任何特定的关联键中搜索值,并返回所有匹配项.

第二个例子向您显示的值("泰勒")在一定的关联键(FIRST_NAME)被发现另一值(true)的另一关联键(使用)被发现,并返回所有匹配(钥匙里的人与名字'泰勒'和被雇用).

/**
 * @param array multidimensional 
 * @param string $search_value The value to search for, ie a specific 'Taylor'
 * @param string $key_to_search The associative key to find it in, ie first_name
 * @param string $other_matching_key The associative key to find in the matches for employed
 * @param string $other_matching_value The value to find in that matching associative key, ie true
 * 
 * @return array keys, ie all the people with the first name 'Taylor' that are employed.
 */
 function search_revisions($dataArray, $search_value, $key_to_search, $other_matching_value = null, $other_matching_key = null) {
    // This function will search the revisions for a certain value
    // related to the associative key you are looking for.
    $keys = array();
    foreach ($dataArray as $key => $cur_value) {
        if ($cur_value[$key_to_search] == $search_value) {
            if (isset($other_matching_key) && isset($other_matching_value)) {
                if ($cur_value[$other_matching_key] == $other_matching_value) {
                    $keys[] = $key;
                }
            } else {
                // I must keep in mind that some searches may have multiple
                // matches and others would not, so leave it open with no continues.
                $keys[] = $key;
            }
        }
    }
    return $keys;
}
Run Code Online (Sandbox Code Playgroud)

使用功能

$data = array(
    array(
        'cust_group' => 6,
        'price' => 13.21,
        'price_qty' => 5
    ),
    array(
        'cust_group' => 8,
        'price' => 15.25,
        'price_qty' => 4
    ),
    array(
        'cust_group' => 8,
        'price' => 12.75,
        'price_qty' => 10
    )
);

$findKey = search_revisions($data,'8', 'cust_group', '10', 'price_qty');
print_r($findKey);
Run Code Online (Sandbox Code Playgroud)

结果

Array ( [0] => 2 ) 
Run Code Online (Sandbox Code Playgroud)


voo*_*417 8

我修改了以下描述函数array_search中的一个示例.函数searchItemsByKey通过$ key从多维数组(N级)返回所有值.也许,它会对某些人有用.例:

 $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
)
Run Code Online (Sandbox Code Playgroud)

功能码:

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;
}
Run Code Online (Sandbox Code Playgroud)


BEJ*_*SAD 6

看起来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'
        )
);
Run Code Online (Sandbox Code Playgroud)

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 mandatory.. Available Values:- ARRAY_FILTER_USE_BOTH OR ARRAY_FILTER_USE_KEY  

$values= print_r(array_value($found)); 
$keys =  print_r(array_keys($found)); 
Run Code Online (Sandbox Code Playgroud)


Usm*_*med 6

您可以为此使用 array_column。

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

print_r($userdb[$user]);
Run Code Online (Sandbox Code Playgroud)

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


Rah*_*hul 5

这是一支相同的内胆

$pic_square = $userdb[array_search($uid,array_column($userdb, 'uid'))]['pic_square'];
Run Code Online (Sandbox Code Playgroud)