PHP:检查多维数组中是否存在值和键

时间:2022-09-25 09:10:16

Just wondering if you can give me a hand with this:

不知道你能不能帮我一下:

I have a multidimensional array...

我有一个多维数组…

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

Any idea about what would be the fastest and most efficient way to check if the array $my_array contains any value with the key "id" and its value 152. I don't need to echo or use any of the values. I just need to check (return true) if the array has any records with the ID "key" and the value "152" in it.

关于检查数组$my_array是否包含任何键“id”及其值152的最快和最有效的方法的任何想法。我不需要重复或使用任何值。我只需要检查(返回true)数组中是否有ID“key”和值“152”的记录。

11 个解决方案

#1


60  

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

#2


20  

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

下面是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;
}

#3


9  

** PHP >= 5.5

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

#4


7  

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:

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

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

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

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

#5


4  

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

假设2-D数组名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;
}

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

正如您所看到的,它实际上只检查包含key_name 'id的任何内部索引是否具有$值。如果key_name 'name' name'也有$value,那么这里的其他一些答案也可能是true

#6


2  

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

Note: array_key_exists call is optional. It just lends itself to code hardiness.

注意:array_key_exists调用是可选的。它只会增加代码的难易性。

#7


1  

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

#8


1  

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

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

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

注意:它将在PHP 5.5+中工作。

#9


1  

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

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

#10


0  

Use an array_map()

使用一个到()

$options is the array in which you are searching.

$options是您正在搜索的数组。

$arr = array_map(function($ar) {
    if(array_key_exists('name_of_the_key_you_search_for',$ar)){
        return true;
    }else{
        return false;
    }
},$options  );
var_dump($arr); //just for test, remove in the code

#11


0  

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

#1


60  

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

#2


20  

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

下面是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;
}

#3


9  

** PHP >= 5.5

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

#4


7  

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:

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

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

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

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

#5


4  

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

假设2-D数组名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;
}

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

正如您所看到的,它实际上只检查包含key_name 'id的任何内部索引是否具有$值。如果key_name 'name' name'也有$value,那么这里的其他一些答案也可能是true

#6


2  

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

Note: array_key_exists call is optional. It just lends itself to code hardiness.

注意:array_key_exists调用是可选的。它只会增加代码的难易性。

#7


1  

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

#8


1  

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

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

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

注意:它将在PHP 5.5+中工作。

#9


1  

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

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

#10


0  

Use an array_map()

使用一个到()

$options is the array in which you are searching.

$options是您正在搜索的数组。

$arr = array_map(function($ar) {
    if(array_key_exists('name_of_the_key_you_search_for',$ar)){
        return true;
    }else{
        return false;
    }
},$options  );
var_dump($arr); //just for test, remove in the code

#11


0  

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