如何检查多维数组的任何子数组中的特定键是否存在特定值?

发布于 2024-11-28 08:07:25 字数 580 浏览 3 评论 0原文

我需要在多维数组中搜索任何索引子数组中的特定值。

换句话说,我需要检查多维数组的单个列中的值。如果该值存在于多维数组中的任何位置,我想返回 true 否则 false

$my_array = array(    
    0 =>  array(  
        "name"   => "john",  
        "id"    =>  4  
    ),  
    1   =>  array(  
        "name" =>  "mark",  
        "id" => 152  
    ), 
    2   =>  array(  
        "name" =>  "Eduard",  
        "id" => 152  
    )
);

我想知道检查数组是否最快、最有效的方法>$my_array 包含一个带有“id”键的值。例如,如果 id => 152 在多维数组中的任何位置,我希望 true

I need to search a multidimensional array for a specific value in any of the indexed subarrays.

In other words, I need to check a single column of the multidimensional array for a value. If the value exists anywhere in the multidimensional array, I would like to return true otherwise false

$my_array = array(    
    0 =>  array(  
        "name"   => "john",  
        "id"    =>  4  
    ),  
    1   =>  array(  
        "name" =>  "mark",  
        "id" => 152  
    ), 
    2   =>  array(  
        "name" =>  "Eduard",  
        "id" => 152  
    )
);

I would like to know the fastest and most efficient way to check if the array $my_array contains a value with the key "id". For example, if id => 152 anywhere in the multidimensional array, I would like true.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(18

咽泪装欢 2024-12-05 08:07:25

没有什么比简单的循环更快的了。您可以混合搭配一些数组函数来完成此操作,但它们也只是作为循环实现。

function whatever($array, $key, $val) {
    foreach ($array as $item)
        if (isset($item[$key]) && $item[$key] == $val)
            return true;
    return false;
}

Nothing will be faster than a simple loop. You can mix-and-match some array functions to do it, but they'll just be implemented as a loop too.

function whatever($array, $key, $val) {
    foreach ($array as $item)
        if (isset($item[$key]) && $item[$key] == $val)
            return true;
    return false;
}
楠木可依 2024-12-05 08:07:25

最简单的方法是这样的:

$my_array = array(    
    0 =>  array(  
        "name"   => "john",  
        "id"    =>  4  
    ),  
    1   =>  array(  
        "name" =>  "mark",  
        "id" => 152  
    ), 
    2   =>  array(  
        "name" =>  "Eduard",  
        "id" => 152  
    )
);

if (array_search(152, array_column($my_array, 'id')) !== FALSE) {
  echo 'FOUND!';
} else {
  echo 'NOT FOUND!';
}

The simplest way is this:

$my_array = array(    
    0 =>  array(  
        "name"   => "john",  
        "id"    =>  4  
    ),  
    1   =>  array(  
        "name" =>  "mark",  
        "id" => 152  
    ), 
    2   =>  array(  
        "name" =>  "Eduard",  
        "id" => 152  
    )
);

if (array_search(152, array_column($my_array, 'id')) !== FALSE) {
  echo 'FOUND!';
} else {
  echo 'NOT FOUND!';
}
小…楫夜泊 2024-12-05 08:07:25

** PHP >= 5.5

就可以使用这个

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

让我们假设这个多维数组:

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

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

** PHP >= 5.5

simply u can use this

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

Let's suppose this multi dimensional array:

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

$key = array_search(40489, array_column($userdb, 'uid'));
洒一地阳光 2024-12-05 08:07:25

这是 Dan Grossman 答案的更新版本,它将迎合多维数组(我所追求的):

function find_key_value($array, $key, $val)
{
    foreach ($array as $item)
    {
        if (is_array($item) && find_key_value($item, $key, $val)) return true;

        if (isset($item[$key]) && $item[$key] == $val) return true;
    }

    return false;
}

Here is an updated version of Dan Grossman's answer which will cater for multidimensional arrays (what I was after):

function find_key_value($array, $key, $val)
{
    foreach ($array as $item)
    {
        if (is_array($item) && find_key_value($item, $key, $val)) return true;

        if (isset($item[$key]) && $item[$key] == $val) return true;
    }

    return false;
}
〆一缕阳光ご 2024-12-05 08:07:25

如果您必须进行大量“id”查找并且速度应该非常快,您应该使用包含所有“ids”作为键的第二个数组:

$lookup_array=array();

foreach($my_array as $arr){
    $lookup_array[$arr['id']]=1;
}

现在您可以非常快速地检查现有 id,例如:

echo (isset($lookup_array[152]))?'yes':'no';

If you have to make a lot of "id" lookups and it should be really fast you should use a second array containing all the "ids" as keys:

$lookup_array=array();

foreach($my_array as $arr){
    $lookup_array[$arr['id']]=1;
}

Now you can check for an existing id very fast, for example:

echo (isset($lookup_array[152]))?'yes':'no';
记忆消瘦 2024-12-05 08:07:25

@Elias Van Ootegan 在评论中提供了一个好的解决方案:

$ids = array_column($array, 'id', 'id');
echo isset($ids[40489])?"Exist":"Not Exist";

我尝试过并为我工作,谢谢伙计。

已编辑

注意:它将在 PHP 5.5+ 中运行

A good solution can be one provided by @Elias Van Ootegan in a comment that is:

$ids = array_column($array, 'id', 'id');
echo isset($ids[40489])?"Exist":"Not Exist";

I tried it and worked for me, thanks buddy.

Edited

Note: It will work in PHP 5.5+

大姐,你呐 2024-12-05 08:07:25

TMTOWTDI。以下是按复杂程度排列的几种解决方案。

(关于复杂性的简短入门如下):O(n) 或“big o”表示最坏情况,其中 n 表示数组,o(n) 或“little o”表示最佳情况。离散数学长话短说,您只需要担心最坏的情况,并确保它不是 n ^ 2n! 。它更多的是随着n 的增加计算时间的变化,而不是总体计算时间。 维基百科有一篇关于计算(即时间复杂度)的好文章

如果说经验教会了我什么的话,那就是花太多时间优化程序的小细节显然是浪费时间,最好花在更好的事情上——任何事——更好。

解决方案 0:O(n) / o(1) 复杂度:

此解决方案的最佳情况是 1 次比较 - 1 次循环迭代,但仅提供匹配值就位的情况数组的 0。最坏的情况是它不在数组中,因此必须迭代数组的每个元素。

foreach ($my_array as $sub_array) {
    if (@$sub_array['id'] === 152) {
        return true;
    }
}
return false;

解决方案 1:O(n) / o(n) 复杂度:

此解决方案必须循环遍历整个数组,无论匹配值在哪里,因此它始终为 n 遍历数组。

return 0 < count(
    array_filter(
        $my_array,
        function ($a) {
            return array_key_exists('id', $a) && $a['id'] == 152;
        }
    )
);

解决方案 2:O(n log n) / o(n log n) 复杂度:

哈希插入是 log n 的来源; n 哈希插入 = n * log n。最后有一个哈希查找,这是另一个 log n 但它没有包含在内,因为这就是离散数学的工作原理。

$existence_hash = [];
foreach ($my_array as $sub_array) {
    $existence_hash[$sub_array['id']] = true;
}
return @$existence_hash['152'];

TMTOWTDI. Here are several solutions in order of complexity.

(Short primer on complexity follows):O(n) or "big o" means worst case scenario where n means the number of elements in the array, and o(n) or "little o" means best case scenario. Long discrete math story short, you only really have to worry about the worst case scenario, and make sure it's not n ^ 2 or n!. It's more a measure of change in computing time as n increases than it is overall computing time. Wikipedia has a good article about computational aka time complexity.

If experience has taught me anything, it's that spending too much time optimizing your programs' little-o is a distinct waste of time better spent doing something - anything - better.

Solution 0: O(n) / o(1) complexity:

This solution has a best case scenario of 1 comparison - 1 iteration thru the loop, but only provided the matching value is in position 0 of the array. The worst case scenario is it's not in the array, and thus has to iterate over every element of the array.

foreach ($my_array as $sub_array) {
    if (@$sub_array['id'] === 152) {
        return true;
    }
}
return false;

Solution 1: O(n) / o(n) complexity:

This solution must loop thru the entire array no matter where the matching value is, so it's always going to be n iterations thru the array.

return 0 < count(
    array_filter(
        $my_array,
        function ($a) {
            return array_key_exists('id', $a) && $a['id'] == 152;
        }
    )
);

Solution 2: O(n log n) / o(n log n) complexity:

A hash insertion is where the log n comes from; n hash insertions = n * log n. There's a hash lookup at the end which is another log n but it's not included because that's just how discrete math works.

$existence_hash = [];
foreach ($my_array as $sub_array) {
    $existence_hash[$sub_array['id']] = true;
}
return @$existence_hash['152'];
给不了的爱 2024-12-05 08:07:25

我看到这篇文章希望做同样的事情,并提出了我自己的解决方案,我想为该页面的未来访问者提供(并看看这样做是否会出现我没有预见到的任何问题)。

如果您想获得简单的 truefalse 输出,并且希望使用一行代码而不使用函数或循环来完成此操作,您可以序列化数组,然后使用 < code>stripos 搜索值:

stripos(serialize($my_array),$needle)

这似乎对我有用。

I came upon this post looking to do the same and came up with my own solution I wanted to offer for future visitors of this page (and to see if doing this way presents any problems I had not forseen).

If you want to get a simple true or false output and want to do this with one line of code without a function or a loop you could serialize the array and then use stripos to search for the value:

stripos(serialize($my_array),$needle)

It seems to work for me.

十六岁半 2024-12-05 08:07:25

就像你的问题一样,这实际上是一个简单的二维数组不是更好吗?看一下 -

假设您的二维数组名称 $my_array 和要查找的值是 $id

function idExists($needle='', $haystack=array()){
    //now go through each internal array
    foreach ($haystack as $item) {
        if ($item['id']===$needle) {
            return true;
        }
    }
    return false;
}

并调用它:

idExists($id, $my_array);

如您所见,它实际上只检查是否有任何仅包含 key_name 'id' 的内部索引,是否有您的 $value 。如果 key_name 'name' 也有 $value ,这里的其他一些答案也可能结果为 true

As in your question, which is actually a simple 2-D array wouldn't it be better? Have a look-

Let say your 2-D array name $my_array and value to find is $id

function idExists($needle='', $haystack=array()){
    //now go through each internal array
    foreach ($haystack as $item) {
        if ($item['id']===$needle) {
            return true;
        }
    }
    return false;
}

and to call it:

idExists($id, $my_array);

As you can see, it actually only check if any internal index with key_name 'id' only, have your $value. Some other answers here might also result true if key_name 'name' also has $value

独自←快乐 2024-12-05 08:07:25

您可以仅使用两个参数来使用它

function whatever($array, $val) {
    foreach ($array as $item)
        if (isset($item) && in_array($val,$item))
            return 1;
    return 0;
}

You can use this with only two parameter

function whatever($array, $val) {
    foreach ($array as $item)
        if (isset($item) && in_array($val,$item))
            return 1;
    return 0;
}
只涨不跌 2024-12-05 08:07:25

我不知道这对性能来说是好是坏,但这里有一个替代方案:

$keys = array_map(function($element){return $element['id'];}, $my_array);
$flipped_keys = array_flip($keys);
if(isset($flipped_keys[40489]))
{
    // true
}

I don't know if this is better or worse for performance, but here is an alternative:

$keys = array_map(function($element){return $element['id'];}, $my_array);
$flipped_keys = array_flip($keys);
if(isset($flipped_keys[40489]))
{
    // true
}
谈情不如逗狗 2024-12-05 08:07:25

isset 与 array_key_exits 之间的不同
isset() 和 array_key_exists() 有什么区别?

== 与 === 之间的不同 PHP 相等 (== double equals) 如何) 和恒等(=== 三等号)比较运算符有何不同?

function specificValue(array $array,$key,$val) {
    foreach ($array as $item)
        if (array_key_exits($item[$key]) && $item[$key] === $val)
            return true;
    return false;
}

different between isset vs array_key_exits
What's the difference between isset() and array_key_exists()?

different between == vs === How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ?

function specificValue(array $array,$key,$val) {
    foreach ($array as $item)
        if (array_key_exits($item[$key]) && $item[$key] === $val)
            return true;
    return false;
}
段念尘 2024-12-05 08:07:25

您可以创建一个子数组队列并循环每个子数组:

function existsKeyValue($myArray, $key, $value) {
    $queue = [$myArray]; //creating a queue of a single element, which is our outermost array

    //when we reach the count of the queue we looped all inner loops as well and failed to find the item
    for ($index = 0; $index < count($queue); $index++) {
        //Looping the current array, finding the key and the value
        foreach ($queue[$index] as $k => &$v) {
            //If they match the search, then we can return true
            if (($key === $k) && ($value === $v)) {
                return true;
            }
            //We need to make sure we did not already loop our current array to avoid infinite cycles
            if (is_array($v)) $queue[]=$v;
        }
    }
    return false;
}

$my_array = array(    
    0 =>  array(  
        "name"   => "john",  
        "id"    =>  4  
    ),  
    1   =>  array(  
        "name" =>  "mark",  
        "id" => 152  
    ), 
    2   =>  array(  
        "name" =>  "Eduard",  
        "id" => 152  
    )
);

echo var_dump(existsKeyValue($my_array, 'id', 152));

You can create a queue of sub-arrays and loop each:

function existsKeyValue($myArray, $key, $value) {
    $queue = [$myArray]; //creating a queue of a single element, which is our outermost array

    //when we reach the count of the queue we looped all inner loops as well and failed to find the item
    for ($index = 0; $index < count($queue); $index++) {
        //Looping the current array, finding the key and the value
        foreach ($queue[$index] as $k => &$v) {
            //If they match the search, then we can return true
            if (($key === $k) && ($value === $v)) {
                return true;
            }
            //We need to make sure we did not already loop our current array to avoid infinite cycles
            if (is_array($v)) $queue[]=$v;
        }
    }
    return false;
}

$my_array = array(    
    0 =>  array(  
        "name"   => "john",  
        "id"    =>  4  
    ),  
    1   =>  array(  
        "name" =>  "mark",  
        "id" => 152  
    ), 
    2   =>  array(  
        "name" =>  "Eduard",  
        "id" => 152  
    )
);

echo var_dump(existsKeyValue($my_array, 'id', 152));

贪恋 2024-12-05 08:07:25

array_column 返回数组单列的值,我们可以通过 in_array 搜索这些值的特定值

if (in_array(152, array_column($my_array, 'id'))) {
    echo 'FOUND!';
} else {
    echo 'NOT FOUND!';
}

array_column returns the values of a single column of an array and we can search for a specific value for those via in_array

if (in_array(152, array_column($my_array, 'id'))) {
    echo 'FOUND!';
} else {
    echo 'NOT FOUND!';
}
桃气十足 2024-12-05 08:07:25

只需使用 array_column 即可,如下例所示:

$my_array = [
    [
        "name"  => "john",  
        "id"    =>  4  
    ],  
    [
        "name"  =>  "mark",  
        "id"    => 152  
    ], 
    [
        "name"  =>  "Eduard",  
        "id"    => 152  
    ]
];
var_dump(in_array(152, array_column($my_array, 'id'))); // true

Just use array_column as in below example:

$my_array = [
    [
        "name"  => "john",  
        "id"    =>  4  
    ],  
    [
        "name"  =>  "mark",  
        "id"    => 152  
    ], 
    [
        "name"  =>  "Eduard",  
        "id"    => 152  
    ]
];
var_dump(in_array(152, array_column($my_array, 'id'))); // true
海的爱人是光 2024-12-05 08:07:25

尝试使用下面的代码。它应该适用于任何类型的多维数组搜索。

在这里您可以看到实时演示示例

function multi_array_search($search_for, $search_in) {
    foreach ($search_in as $element) {
        if ( ($element === $search_for) ){
            return true;
        }elseif(is_array($element)){
            $result = multi_array_search($search_for, $element);
            if($result == true)
                return true;
        }
    }
    return false;
}

Try with this below code. It should be working fine for any kind of multidimensional array search.

Here you can see LIVE DEMO EXAMPLE

function multi_array_search($search_for, $search_in) {
    foreach ($search_in as $element) {
        if ( ($element === $search_for) ){
            return true;
        }elseif(is_array($element)){
            $result = multi_array_search($search_for, $element);
            if($result == true)
                return true;
        }
    }
    return false;
}
很酷又爱笑 2024-12-05 08:07:25
function checkMultiArrayValue($array) {
        global $test;
        foreach ($array as $key => $item) {

            if(!empty($item) && is_array($item)) {
                checkMultiArrayValue($item);
            }else {
                if($item)
                 $test[$key] = $item;

            }
        }
        return $test;   
    }

 $multiArray = array(    
                0 =>  array(  
                      "country"   => "",  
                      "price"    => 4,  
                      "discount-price" => 0,  
               ),);

$test = checkMultiArrayValue($multiArray);
echo "<pre>"
print_r($test);

将返回具有索引和值的数组

function checkMultiArrayValue($array) {
        global $test;
        foreach ($array as $key => $item) {

            if(!empty($item) && is_array($item)) {
                checkMultiArrayValue($item);
            }else {
                if($item)
                 $test[$key] = $item;

            }
        }
        return $test;   
    }

 $multiArray = array(    
                0 =>  array(  
                      "country"   => "",  
                      "price"    => 4,  
                      "discount-price" => 0,  
               ),);

$test = checkMultiArrayValue($multiArray);
echo "<pre>"
print_r($test);

Will return array who have index and value

自我难过 2024-12-05 08:07:25

我编写了以下函数来确定多维数组是否部分包含某个值。

function findKeyValue ($array, $needle, $value, $found = false){
    foreach ($array as $key => $item){
        // Navigate through the array completely.
        if (is_array($item)){
            $found = $this->findKeyValue($item, $needle, $value, $found);
        }

        // If the item is a node, verify if the value of the node contains
        // the given search parameter. E.G.: 'value' <=> 'This contains the value'
        if ( ! empty($key) && $key == $needle && strpos($item, $value) !== false){
            return true;
        }
    }

    return $found;
}

像这样调用该函数:

$this->findKeyValue($array, $key, $value);

I wrote the following function in order to determine if an multidimensional array partially contains a certain value.

function findKeyValue ($array, $needle, $value, $found = false){
    foreach ($array as $key => $item){
        // Navigate through the array completely.
        if (is_array($item)){
            $found = $this->findKeyValue($item, $needle, $value, $found);
        }

        // If the item is a node, verify if the value of the node contains
        // the given search parameter. E.G.: 'value' <=> 'This contains the value'
        if ( ! empty($key) && $key == $needle && strpos($item, $value) !== false){
            return true;
        }
    }

    return $found;
}

Call the function like this:

$this->findKeyValue($array, $key, $value);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文