PHP多维数组按值搜索

本文翻译自:PHP multidimensional array search by value

I have an array where I want to search the uid and get the key of the array. 我有一个数组,我想在其中搜索uid并获取该数组的键。

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 . 函数调用search_by_uid(100) (第一个用户的uid)应返回0

The function call search_by_uid(40489) should return 2 . 函数调用search_by_uid(40489)应该返回2

I tried making loops, but I want a faster executing code. 我尝试进行循环,但是我想要更快的执行代码。


#1楼

参考:https://stackoom.com/question/rWY2/PHP多维数组按值搜索


#2楼

I know this was already answered, but I used this and extended it a little more in my code so that you didn't have search by only the uid. 我知道已经回答了这个问题,但是我在代码中使用了它并对其进行了扩展,以便您不必仅通过uid进行搜索。 I just want to share it for anyone else who may need that functionality. 我只想与可能需要此功能的其他任何人共享它。

Here's my example and please bare in mind this is my first answer. 这是我的示例,请记住,这是我的第一个答案。 I took out the param array because I only needed to search one specific array, but you could easily add it in. I wanted to essentially search by more than just the uid. 我删除了param数组,因为我只需要搜索一个特定的数组,但是您可以轻松地将其添加到其中。我想本质上可以搜索的不仅仅是uid。

Also, in my situation there may be multiple keys to return as a result of searching by other fields that may not be unique. 同样,在我的情况下,由于其他字段可能不是唯一的,因此可能有多个键要返回。

 /**
     * @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;
    }

Later, I ended up writing this to allow me to search for another value and associative key. 后来,我最终编写了此代码,以允许我搜索另一个值和关联键。 So my first example allows you to search for a value in any specific associative key, and return all the matches. 因此,我的第一个示例允许您在任何特定的关联键中搜索值,然后返回所有匹配项。

This second example shows you where a value ('Taylor') is found in a certain associative key (first_name) AND another value (true) is found in another associative key (employed), and returns all matches (Keys where people with first name 'Taylor' AND are employed). 其中一个值(“泰勒”)在一定的关联键(FIRST_NAME),另一个值(true),发现这第二个例子说明你在其他关联键(使用)被发现,并返回所有匹配(钥匙里的人与名字使用“泰勒” AND)。

/**
 * @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;
}

Use of function 使用功能

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

Result 结果

Array ( [0] => 2 ) 

#3楼

Building off Jakub's excellent answer , here is a more generalized search that will allow the key to specified (not just for uid): 基于Jakub的出色答案 ,这是一种更通用的搜索,该搜索将允许指定键(不仅限于uid):

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

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


#4楼

I had to use un function which finds every elements in an array. 我必须使用un函数来查找数组中的每个元素。 So I modified the function done by Jakub Truneček as follow: 因此,我修改了JakubTruneček完成的功能,如下所示:

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;
}

#5楼

I modified one of examples below description function array_search . 我修改了以下描述函数array_search的示例之一 Function searchItemsByKey return all value(s) by $key from multidimensional array ( N levels). searchItemsByKey函数从多维数组(N个级别)中以$ key返回所有值。 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;
}

#6楼

you can use this function ; 您可以使用此功能; https://github.com/serhatozles/ArrayAdvancedSearch https://github.com/serhatozles/ArrayAdvancedSearch

<?php 
include('ArraySearch.php');

$query = "a='Example World' and b>='2'";

$Array = array(
'a' => array('d' => '2'),
array('a' => 'Example World','b' => '2'),
array('c' => '3'), array('d' => '4'),
);

$Result = ArraySearch($Array,$query,1);

echo '<pre>';
print_r($Result);
echo '</pre>'; 

// Output:
// Array
// (
//    [0] => Array
//        (
//            [a] => Example World
//            [b] => 2
//        )
//
// )
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值