简体   繁体   English

PHP多维数组键搜索

[英]PHP multidimension array key search

So, I have multidimensional array (for example): 因此,我有多维数组(例如):

array[1][22]['name']
array[1][33]['name']
array[2][44]['name']
array[3][55]['name']

I know last array key(it's ID) (for example - [44]), how can I find value of [name] for known key? 我知道最后一个数组键(它的ID)(例如-[44]),如何找到已知键的[name]值?

In my guess I need something like array_search, but for key and in multidimensional array... 我猜我需要像array_search这样的东西,但是对于键和多维数组...

Here's a simple way with PHP >= 5.5.0. 这是使用PHP> = 5.5.0的简单方法。 This assumes there is only one key 44 in the array: 假设数组中只有一个键44

echo array_column($array, 44)[0]['name'];
// or
echo current(array_column($array, 44))['name'];

Earlier versions: 早期版本:

foreach($array as $k => $v) { if(isset($v[44])) echo $v[44]['name']; }

You are better off changing your array structure: 最好更改数组结构:

$array = [
  22 => [ 'name' => 'A'],
  33 => [ 'name' => 'B'],
  44 => [ 'name' => 'C'],
  55 => [ 'name' => 'D'],
];

and simply write 并简单地写

$array[44]['name']

Wouldn't it be better to optimize your array for this search, for instance build another one with IDs as keys and references to the data as values? 为此搜索优化数组是否会更好,例如,以ID作为键并以数据引用作为值来构建另一个数组?

When building your array you could:
$IDsIndex = array();
foreach(...) {
    $IDsIndex[$ID] = &$data;
}

and then: 接着:

$IDsIndex[44]['name'];

I have a function that seems to work for me. 我有一个似乎对我有用的功能。 Let me know if you find it lacking. 如果您发现缺少它,请告诉我。 Note: It has not been tested for performance on massive arrays or objects. 注意:尚未对大型阵列或对象的性能进行测试。

function arrayKeySearch(array $haystack, string $search_key, &$output_value, int $occurence = 1){
    $result             = false;
    $search_occurences  = 0;
    $output_value       = null;
    if($occurence < 1){ $occurence = 1; }
    foreach($haystack as $key => $value){
        if($key == $search_key){
            $search_occurences++;
            if($search_occurences == $occurence){
                $result         = true;
                $output_value = $value;
                break;
            }
        }else if(is_array($value) || is_object($value)){
            if(is_object($value)){
                $value = (array)$value;
            }
            $result = arrayKeySearch($value, $search_key, $output_value, $occurence);
            if($result){
                break;
            }
        }
    }
    return $result;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM