PHP multidimensional array search by value

2018-12-31 01:38发布

I have an array where I want to search the uid and get the key of the array.

Examples

Assume we have the following 2-dimensional array:

$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'
    )
);

The function call search_by_uid(100) (uid of first user) should return 0.

The function call search_by_uid(40489) should return 2.

I tried making loops, but I want a faster executing code.

标签: php
21条回答
看风景的人
2楼-- · 2018-12-31 01:52

Looks array_filter will be suitable solution for this...

$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 Code

<?php 
$search = 5465;
$found = array_filter($userdb,function($v,$k) use ($search){
  return $v['uid'] => $search;
}) 

$values= print_r(array_value($found)); 
$keys =  print_r(array_keys($found)); 
查看更多
梦醉为红颜
3楼-- · 2018-12-31 01:53

In later versions of PHP (>= 5.5.0) you can use this one-liner:

$key = array_search('100', array_column($userdb, 'uid'));
查看更多
呛了眼睛熬了心
4楼-- · 2018-12-31 01:54

I modified one of examples below description function array_search. Function searchItemsByKey return all value(s) by $key from multidimensional array ( N levels). Perhaps , it would be useful for somebody. Example:

 $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 code:

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;
}
查看更多
永恒的永恒
5楼-- · 2018-12-31 01:56

Expanding on the function @mayhem created, this example would be more of a "fuzzy" search in case you just want to match part (most) of a search string:

 function searchArrayKeyVal($sKey, $id, $array) {
    foreach ($array as $key => $val) {
        if (strpos(strtolower($val[$sKey]), strtolower(trim($id))) !== false) {
            return $key;
        }
    }
         return false;
 }

For example the value in the array is Welcome to New York! and you wanted the first instance of just "New York!"

查看更多
孤独寂梦人
6楼-- · 2018-12-31 01:58

Here is one liner for the same,

$pic_square = $userdb[array_search($uid,array_column($userdb, 'uid'))]['pic_square'];
查看更多
泪湿衣
7楼-- · 2018-12-31 01:59
function searchForId($id, $array) {
   foreach ($array as $key => $val) {
       if ($val['uid'] === $id) {
           return $key;
       }
   }
   return null;
}

This will work. You should call it like this:

$id = searchForId('100', $userdb);

It is important to know that if you are using === operator compared types have to be exactly same, in this example you have to search string or just use == instead ===.

Based on angoru answer. In later versions of PHP (>= 5.5.0) you can use one-liner.

$key = array_search('100', array_column($userdb, 'uid'));

Here is documentation: http://php.net/manual/en/function.array-column.php.

查看更多
登录 后发表回答