简体   繁体   English

如何从嵌套数组中获取基于值的键?

[英]How to get key based on value from a nested array?

This is an example of a nested array I'm working with. 这是我正在使用的嵌套数组的示例。 The "keys" representing locations are 720, and 715. The nested array values are services at said locations. 代表位置的“键”是720和715。嵌套的数组值是所述位置的服务。

As you can tell from the values some are duplicated, and some are unique. 从这些值可以看出,有些是重复的,有些是唯一的。 I want to be able to take a single value or array such as 4512, 1110, 685 and then look up the relevant key. 我希望能够采用单个值或数组,例如4512、1110、685,然后查找相关的键。

So 4512 would return 720. 因此4512将返回720。

Done so far is: 1) Generated what I believe is a properly formatted array 2) Retrieved intersected values within nested arrays 到目前为止,完成的操作是:1)生成了我认为是格式正确的数组2)检索了嵌套数组中的相交值

Problem Summary: How to get the key from one of the values. 问题摘要:如何从其中一个值获取密钥。 I'm sorry but I tried array_search() without any luck. 抱歉,我没有任何运气尝试过array_search()。

Any help is appreciated, i'm still learning about arrays. 感谢任何帮助,我仍在学习数组。 Thanks. 谢谢。

array(
    2
)
    {
    [720] => array(
        4
    )
        {
        [0] => int(4512) [1] => int(1110) [2] => int(1803) [3] => int(669)
        }

    [715] => array(
        3
    )
        {
        [0] => int(1803) [1] => int(685) [2] => int(669)
        }
    }

Trying to search through that structure as-is is going to waste a lot of time since all of the entries need to be examined every time, but if you invert it it can be made much more efficient by leveraging PHP's array indexes for a direct lookup. 试图通过结构,是会浪费很多时间,因为所有的项目需要在每次检查中进行搜索,但如果你反其道而行,可以通过利用PHP的数组索引直接查找更有效的制造。 eg: 例如:

$arr = [
  4512 => 720,
  1110 => 720,
  1803 => 715
];

echo $arr[4512]; // 720

Even creating a simple index like this in parallel to the main data structure will allow you to benefit from it. 甚至与主数据结构并行创建这样的简单索引也将使您从中受益。

As mentioned by Sammitch , if you have a large structure or plan on doing many queries, a linear search through the array inspecting each element on every search is an expensive and unnecessary operation. Sammitch所述 ,如果您有大型结构或计划执行许多查询,则通过数组进行线性搜索以检查每次搜索中的每个元素是一项昂贵且不必要的操作。 If you use the PHP function array_flip() , you can invert keys and values and index right into the array in constant time (meaning instantly regardless of how big your array is, if you haven't studied time complexity just yet). 如果使用PHP函数array_flip() ,则可以在恒定时间内将键和值反转并直接索引到数组中(这意味着无论数组有多大,如果您还没有研究时间复杂度 ,都可以立即获得索引)。

One snag: array_flip() doesn't work when the input array's values aren't hashable types, as is the case here. 一个障碍:当输入数组的值不是可哈希的类型时, array_flip()不起作用,就像这里的情况。 So we write our own array_flip() that turns array values into keys. 因此,我们编写了自己的array_flip() ,它将数组值转换为键。

I'm assuming any duplicate values should produce an array of the keys that map to them in the flipped array. 我假设任何重复的值都应产生一个键数组,该键映射到翻转数组中。 Changing that policy to take the last or first key results in less code, if desired. 如果需要,将策略更改为采用最后一个或第一个密钥会减少代码量。

function flip($arr) {
    $flipped = [];

    foreach ($arr as $k => $v) {
        foreach ($v as $e) {
            if (!array_key_exists($e, $flipped)) {
                $flipped[$e] = $k;
            }
            else {
                if (is_array($flipped[$e])) {
                    $flipped[$e][] = $k;
                }
                else {
                    $flipped[$e] = [$flipped[$e], $k];
                }
            }
        }
    }

    return $flipped;
}

function find($needle, $haystack) {
    return array_key_exists($needle, $haystack) ? $haystack[$needle] : false;
}

$arr = [
  720 => [4512, 1110, 1803, 669],
  715 => [1803, 685, 669]
];
$flipped = flip($arr);

echo "the flipped array: \n";
print_r($flipped);

echo "\n\nsearching for 1803: \n";
print_r(find(1803, $flipped));
echo "\n\n";

echo "searching for 1: \n";
print_r(find(1, $flipped));
echo "\n\n";

echo "searching for 4512: \n";
print_r(find(4512, $flipped));
echo "\n\n";

Output: 输出:

the flipped array: 
Array
(
    [4512] => 720
    [1110] => 720
    [1803] => Array
        (
            [0] => 720
            [1] => 715
        )

    [669] => Array
        (
            [0] => 720
            [1] => 715
        )

    [685] => 715
)


searching for 1803: 
Array
(
    [0] => 720
    [1] => 715
)


searching for 1: 


searching for 4512: 
720

Try it here 在这里尝试

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

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