in_array() 和多维数组

发布于 2024-10-01 01:57:25 字数 378 浏览 0 评论 0 原文

我使用 in_array() 来检查数组中是否存在某个值,如下所示,

$a = array("Mac", "NT", "Irix", "Linux");
if (in_array("Irix", $a)) 
{
    echo "Got Irix";
}

//print_r($a);

但是多维数组(如下)怎么样 - 如何检查该值是否存在于多数组中?

$b = array(array("Mac", "NT"), array("Irix", "Linux"));

print_r($b);

或者当涉及多维数组时我不应该使用 in_array()

I use in_array() to check whether a value exists in an array like below,

$a = array("Mac", "NT", "Irix", "Linux");
if (in_array("Irix", $a)) 
{
    echo "Got Irix";
}

//print_r($a);

but what about an multidimensional array (below) - how can I check that value whether it exists in the multi-array?

$b = array(array("Mac", "NT"), array("Irix", "Linux"));

print_r($b);

or I shouldn't be using in_array() when comes to the multidimensional array?

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

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

发布评论

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

评论(24

孤千羽 2024-10-08 01:57:25

in_array() 不适用于多维数组。您可以编写一个递归函数来为您执行此操作:

function in_array_r($needle, $haystack, $strict = false) {
    foreach ($haystack as $item) {
        if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
            return true;
        }
    }

    return false;
}

用法:

$b = array(array("Mac", "NT"), array("Irix", "Linux"));
echo in_array_r("Irix", $b) ? 'found' : 'not found';

in_array() does not work on multidimensional arrays. You could write a recursive function to do that for you:

function in_array_r($needle, $haystack, $strict = false) {
    foreach ($haystack as $item) {
        if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
            return true;
        }
    }

    return false;
}

Usage:

$b = array(array("Mac", "NT"), array("Irix", "Linux"));
echo in_array_r("Irix", $b) ? 'found' : 'not found';
滥情哥ㄟ 2024-10-08 01:57:25

如果您知道要搜索哪一列,则可以使用 array_search() 和 array_column():

$userdb = Array
(
    (0) => Array
        (
            ('uid') => '100',
            ('name') => 'Sandra Shush',
            ('url') => 'urlof100'
        ),

    (1) => Array
        (
            ('uid') => '5465',
            ('name') => 'Stefanie Mcmohn',
            ('url') => 'urlof5465'
        ),

    (2) => Array
        (
            ('uid') => '40489',
            ('name') => 'Michael',
            ('url') => 'urlof40489'
        )
);

if(array_search('urlof5465', array_column($userdb, 'url')) !== false) {
    echo 'value is in multidim array';
}
else {
    echo 'value is not in multidim array';
}

这个想法位于 PHP 手册中 array_search() 的注释部分;

If you know which column to search against, you can use array_search() and array_column():

$userdb = Array
(
    (0) => Array
        (
            ('uid') => '100',
            ('name') => 'Sandra Shush',
            ('url') => 'urlof100'
        ),

    (1) => Array
        (
            ('uid') => '5465',
            ('name') => 'Stefanie Mcmohn',
            ('url') => 'urlof5465'
        ),

    (2) => Array
        (
            ('uid') => '40489',
            ('name') => 'Michael',
            ('url') => 'urlof40489'
        )
);

if(array_search('urlof5465', array_column($userdb, 'url')) !== false) {
    echo 'value is in multidim array';
}
else {
    echo 'value is not in multidim array';
}

This idea is in the comments section for array_search() on the PHP manual;

遇到 2024-10-08 01:57:25

这也会起作用。

function in_array_r($item , $array){
    return preg_match('/"'.preg_quote($item, '/').'"/i' , json_encode($array));
}

用法:

if(in_array_r($item , $array)){
    // found!
}

This will work too.

function in_array_r($item , $array){
    return preg_match('/"'.preg_quote($item, '/').'"/i' , json_encode($array));
}

Usage:

if(in_array_r($item , $array)){
    // found!
}
逆蝶 2024-10-08 01:57:25

这样就可以做到:

foreach($b as $value)
{
    if(in_array("Irix", $value, true))
    {
        echo "Got Irix";
    }
}

in_array 仅对一维数组进行操作,因此您需要循环遍历每个子数组并在每个子数组上运行 in_array

正如其他人所指出的,这仅适用于二维数组。如果您有更多嵌套数组,则递归版本会更好。有关示例,请参阅其他答案。

This will do it:

foreach($b as $value)
{
    if(in_array("Irix", $value, true))
    {
        echo "Got Irix";
    }
}

in_array only operates on a one dimensional array, so you need to loop over each sub array and run in_array on each.

As others have noted, this will only for for a 2-dimensional array. If you have more nested arrays, a recursive version would be better. See the other answers for examples of that.

琉璃繁缕 2024-10-08 01:57:25
$userdb = Array
(
    (0) => Array
        (
            ('uid') => '100',
            ('name') => 'Sandra Shush',
            ('url') => 'urlof100'
        ),

    (1) => Array
        (
            ('uid') => '5465',
            ('name') => 'Stefanie Mcmohn',
            ('url') => 'urlof5465'
        ),

    (2) => Array
        (
            ('uid') => '40489',
            ('name') => 'Michael',
            ('url') => 'urlof40489'
        )
);

$url_in_array = in_array('urlof5465', array_column($userdb, 'url'));

if($url_in_array) {
    echo 'value is in multidim array';
}
else {
    echo 'value is not in multidim array';
}
$userdb = Array
(
    (0) => Array
        (
            ('uid') => '100',
            ('name') => 'Sandra Shush',
            ('url') => 'urlof100'
        ),

    (1) => Array
        (
            ('uid') => '5465',
            ('name') => 'Stefanie Mcmohn',
            ('url') => 'urlof5465'
        ),

    (2) => Array
        (
            ('uid') => '40489',
            ('name') => 'Michael',
            ('url') => 'urlof40489'
        )
);

$url_in_array = in_array('urlof5465', array_column($userdb, 'url'));

if($url_in_array) {
    echo 'value is in multidim array';
}
else {
    echo 'value is not in multidim array';
}
梦年海沫深 2024-10-08 01:57:25

如果你的数组像这样

$array = array(
              array("name" => "Robert", "Age" => "22", "Place" => "TN"), 
              array("name" => "Henry", "Age" => "21", "Place" => "TVL")
         );

使用这个

function in_multiarray($elem, $array,$field)
{
    $top = sizeof($array) - 1;
    $bottom = 0;
    while($bottom <= $top)
    {
        if($array[$bottom][$field] == $elem)
            return true;
        else 
            if(is_array($array[$bottom][$field]))
                if(in_multiarray($elem, ($array[$bottom][$field])))
                    return true;

        $bottom++;
    }        
    return false;
}

例子:echo in_multiarray("22", $array,"Age");

if your array like this

$array = array(
              array("name" => "Robert", "Age" => "22", "Place" => "TN"), 
              array("name" => "Henry", "Age" => "21", "Place" => "TVL")
         );

Use this

function in_multiarray($elem, $array,$field)
{
    $top = sizeof($array) - 1;
    $bottom = 0;
    while($bottom <= $top)
    {
        if($array[$bottom][$field] == $elem)
            return true;
        else 
            if(is_array($array[$bottom][$field]))
                if(in_multiarray($elem, ($array[$bottom][$field])))
                    return true;

        $bottom++;
    }        
    return false;
}

example : echo in_multiarray("22", $array,"Age");

私藏温柔 2024-10-08 01:57:25

对于多维子代: in_array('needle', array_column($arr, 'key'))

对于一维子代: in_array ('needle', call_user_func_array('array_merge', $arr))

For Multidimensional Children: in_array('needle', array_column($arr, 'key'))

For One Dimensional Children: in_array('needle', call_user_func_array('array_merge', $arr))

亣腦蒛氧 2024-10-08 01:57:25

很棒的功能,但它对我不起作用,直到我添加了 if($found) { break; }elseif

function in_array_r($needle, $haystack) {
    $found = false;
    foreach ($haystack as $item) {
    if ($item === $needle) { 
            $found = true; 
            break; 
        } elseif (is_array($item)) {
            $found = in_array_r($needle, $item); 
            if($found) { 
                break; 
            } 
        }    
    }
    return $found;
}

Great function, but it didnt work for me until i added the if($found) { break; } to the elseif

function in_array_r($needle, $haystack) {
    $found = false;
    foreach ($haystack as $item) {
    if ($item === $needle) { 
            $found = true; 
            break; 
        } elseif (is_array($item)) {
            $found = in_array_r($needle, $item); 
            if($found) { 
                break; 
            } 
        }    
    }
    return $found;
}
她如夕阳 2024-10-08 01:57:25

PHP 5.6开始,对于原始答案有一个更好、更干净的解决方案:

对于像这样的多维数组:

$a = array(array("Mac", "NT"), array("Irix", "Linux"))

我们可以使用splat 运算符

return in_array("Irix", array_merge(...$a), true)

如果您有字符串键像这样:

$a = array("a" => array("Mac", "NT"), "b" => array("Irix", "Linux"))

您必须使用 array_values 以避免错误 Cannot unpack array with string keywords

return in_array("Irix", array_merge(...array_values($a)), true)

Since PHP 5.6 there is a better and cleaner solution for the original answer :

With a multidimensional array like this :

$a = array(array("Mac", "NT"), array("Irix", "Linux"))

We can use the splat operator :

return in_array("Irix", array_merge(...$a), true)

If you have string keys like this :

$a = array("a" => array("Mac", "NT"), "b" => array("Irix", "Linux"))

You will have to use array_values in order to avoid the error Cannot unpack array with string keys :

return in_array("Irix", array_merge(...array_values($a)), true)
凑诗 2024-10-08 01:57:25

您始终可以序列化多维数组并执行 strpos

$arr = array(array("Mac", "NT"), array("Irix", "Linux"));

$in_arr = (bool)strpos(serialize($arr),'s:4:"Irix";');

if($in_arr){
    echo "Got Irix!";
}

我使用的内容的各种文档:

You could always serialize your multi-dimensional array and do a strpos:

$arr = array(array("Mac", "NT"), array("Irix", "Linux"));

$in_arr = (bool)strpos(serialize($arr),'s:4:"Irix";');

if($in_arr){
    echo "Got Irix!";
}

Various docs for things I used:

落日海湾 2024-10-08 01:57:25

我相信你现在可以使用 array_key_exists

<?php
$a=array("Mac"=>"NT","Irix"=>"Linux");
if (array_key_exists("Mac",$a))
  {
  echo "Key exists!";
  }
else
  {
  echo "Key does not exist!";
  }
?>

I believe you can just use array_key_exists nowadays:

<?php
$a=array("Mac"=>"NT","Irix"=>"Linux");
if (array_key_exists("Mac",$a))
  {
  echo "Key exists!";
  }
else
  {
  echo "Key does not exist!";
  }
?>
夏末的微笑 2024-10-08 01:57:25

接受的解决方案(在撰写本文时)由jwueller

function in_array_r($needle, $haystack, $strict = false) {
    foreach ($haystack as $item) {
        if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
            return true;
        }
    }

    return false;
}

完全正确,但在进行弱比较时可能会出现意外行为(参数 $strict = false )。

由于 PHP 在比较不同类型的值时的类型杂乱

"example" == 0

,并且

0 == "example"

评估 true 因为 "example" 被转换为 int 并转换为 0

(参见 为什么 PHP 考虑0 等于字符串?)

如果这不是所需的行为,在进行非严格比较之前将数值转换为字符串可能会很方便:

function in_array_r($needle, $haystack, $strict = false) {
    foreach ($haystack as $item) {

        if( ! $strict && is_string( $needle ) && ( is_float( $item ) || is_int( $item ) ) ) {
            $item = (string)$item;
        }

        if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
            return true;
        }
    }

    return false;
}

The accepted solution (at the time of writing) by jwueller

function in_array_r($needle, $haystack, $strict = false) {
    foreach ($haystack as $item) {
        if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
            return true;
        }
    }

    return false;
}

Is perfectly correct but may have unintended behaviuor when doing weak comparison (the parameter $strict = false).

Due to PHP's type juggling when comparing values of different type both

"example" == 0

and

0 == "example"

Evaluates true because "example" is casted to int and turned into 0.

(See Why does PHP consider 0 to be equal to a string?)

If this is not the desired behaviuor it can be convenient to cast numeric values to string before doing a non-strict comparison:

function in_array_r($needle, $haystack, $strict = false) {
    foreach ($haystack as $item) {

        if( ! $strict && is_string( $needle ) && ( is_float( $item ) || is_int( $item ) ) ) {
            $item = (string)$item;
        }

        if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
            return true;
        }
    }

    return false;
}
执手闯天涯 2024-10-08 01:57:25

这是我在 in_array 的 php 手册中找到的第一个此类函数。评论部分中的功能并不总是最好的,但如果它不起作用,您也可以查看那里:)

<?php
function in_multiarray($elem, $array)
    {
        // if the $array is an array or is an object
         if( is_array( $array ) || is_object( $array ) )
         {
             // if $elem is in $array object
             if( is_object( $array ) )
             {
                 $temp_array = get_object_vars( $array );
                 if( in_array( $elem, $temp_array ) )
                     return TRUE;
             }

             // if $elem is in $array return true
             if( is_array( $array ) && in_array( $elem, $array ) )
                 return TRUE;


             // if $elem isn't in $array, then check foreach element
             foreach( $array as $array_element )
             {
                 // if $array_element is an array or is an object call the in_multiarray function to this element
                 // if in_multiarray returns TRUE, than return is in array, else check next element
                 if( ( is_array( $array_element ) || is_object( $array_element ) ) && $this->in_multiarray( $elem, $array_element ) )
                 {
                     return TRUE;
                     exit;
                 }
             }
         }

         // if isn't in array return FALSE
         return FALSE;
    }
?>

This is the first function of this type that I found in the php manual for in_array. Functions in the comment sections aren't always the best but if it doesn't do the trick you can look in there too :)

<?php
function in_multiarray($elem, $array)
    {
        // if the $array is an array or is an object
         if( is_array( $array ) || is_object( $array ) )
         {
             // if $elem is in $array object
             if( is_object( $array ) )
             {
                 $temp_array = get_object_vars( $array );
                 if( in_array( $elem, $temp_array ) )
                     return TRUE;
             }

             // if $elem is in $array return true
             if( is_array( $array ) && in_array( $elem, $array ) )
                 return TRUE;


             // if $elem isn't in $array, then check foreach element
             foreach( $array as $array_element )
             {
                 // if $array_element is an array or is an object call the in_multiarray function to this element
                 // if in_multiarray returns TRUE, than return is in array, else check next element
                 if( ( is_array( $array_element ) || is_object( $array_element ) ) && $this->in_multiarray( $elem, $array_element ) )
                 {
                     return TRUE;
                     exit;
                 }
             }
         }

         // if isn't in array return FALSE
         return FALSE;
    }
?>
世俗缘 2024-10-08 01:57:25

这是我的建议基于 json_encode() 解决方案,其中:

  • 不区分大小写选项
  • 返回计数而不是true
  • < strong>数组中的任何位置(键和值)

如果未找到单词,它仍然返回等于false0

function in_array_count($needle, $haystack, $caseSensitive = true) {
    if(!$caseSensitive) {
        return substr_count(strtoupper(json_encode($haystack)), strtoupper($needle));
    }
    return substr_count(json_encode($haystack), $needle);
}

希望有帮助。

Here is my proposition based on json_encode() solution with :

  • case insensitive option
  • returning the count instead of true
  • anywhere in arrays (keys and values)

If word not found, it still returns 0 equal to false.

function in_array_count($needle, $haystack, $caseSensitive = true) {
    if(!$caseSensitive) {
        return substr_count(strtoupper(json_encode($haystack)), strtoupper($needle));
    }
    return substr_count(json_encode($haystack), $needle);
}

Hope it helps.

吃不饱 2024-10-08 01:57:25

我正在寻找一个函数,可以让我在数组(haystack)中搜索字符串和数组(如针),所以我添加到 @jwueller 的回答

这是我的代码:

/**
 * Recursive in_array function
 * Searches recursively for needle in an array (haystack).
 * Works with both strings and arrays as needle.
 * Both needle's and haystack's keys are ignored, only values are compared.
 * Note: if needle is an array, all values in needle have to be found for it to
 * return true. If one value is not found, false is returned.
 * @param  mixed   $needle   The array or string to be found
 * @param  array   $haystack The array to be searched in
 * @param  boolean $strict   Use strict value & type validation (===) or just value
 * @return boolean           True if in array, false if not.
 */
function in_array_r($needle, $haystack, $strict = false) {
     // array wrapper
    if (is_array($needle)) {
        foreach ($needle as $value) {
            if (in_array_r($value, $haystack, $strict) == false) {
                // an array value was not found, stop search, return false
                return false;
            }
        }
        // if the code reaches this point, all values in array have been found
        return true;
    }

    // string handling
    foreach ($haystack as $item) {
        if (($strict ? $item === $needle : $item == $needle)
            || (is_array($item) && in_array_r($needle, $item, $strict))) {
            return true;
        }
    }
    return false;
}

I was looking for a function that would let me search for both strings and arrays (as needle) in the array (haystack), so I added to the answer by @jwueller.

Here's my code:

/**
 * Recursive in_array function
 * Searches recursively for needle in an array (haystack).
 * Works with both strings and arrays as needle.
 * Both needle's and haystack's keys are ignored, only values are compared.
 * Note: if needle is an array, all values in needle have to be found for it to
 * return true. If one value is not found, false is returned.
 * @param  mixed   $needle   The array or string to be found
 * @param  array   $haystack The array to be searched in
 * @param  boolean $strict   Use strict value & type validation (===) or just value
 * @return boolean           True if in array, false if not.
 */
function in_array_r($needle, $haystack, $strict = false) {
     // array wrapper
    if (is_array($needle)) {
        foreach ($needle as $value) {
            if (in_array_r($value, $haystack, $strict) == false) {
                // an array value was not found, stop search, return false
                return false;
            }
        }
        // if the code reaches this point, all values in array have been found
        return true;
    }

    // string handling
    foreach ($haystack as $item) {
        if (($strict ? $item === $needle : $item == $needle)
            || (is_array($item) && in_array_r($needle, $item, $strict))) {
            return true;
        }
    }
    return false;
}
人间不值得 2024-10-08 01:57:25

我使用此方法适用于任意数量的嵌套并且不需要黑客攻击

<?php
    $blogCategories = [
        'programing' => [
            'golang',
            'php',
            'ruby',
            'functional' => [
                'Erlang',
                'Haskell'
            ]
        ],
        'bd' => [
            'mysql',
            'sqlite'
        ]
    ];
    $it = new RecursiveArrayIterator($blogCategories);
    foreach (new RecursiveIteratorIterator($it) as $t) {
        $found = $t == 'Haskell';
        if ($found) {
           break;
        }
    }

I used this method works for any number of nested and not require hacking

<?php
    $blogCategories = [
        'programing' => [
            'golang',
            'php',
            'ruby',
            'functional' => [
                'Erlang',
                'Haskell'
            ]
        ],
        'bd' => [
            'mysql',
            'sqlite'
        ]
    ];
    $it = new RecursiveArrayIterator($blogCategories);
    foreach (new RecursiveIteratorIterator($it) as $t) {
        $found = $t == 'Haskell';
        if ($found) {
           break;
        }
    }
耀眼的星火 2024-10-08 01:57:25

请尝试:

in_array("irix",array_keys($b))
in_array("Linux",array_keys($b["irix"])

我不确定是否需要,但这可能适合您的要求

Please try:

in_array("irix",array_keys($b))
in_array("Linux",array_keys($b["irix"])

Im not sure about the need, but this might work for your requirement

樱花细雨 2024-10-08 01:57:25

它也可以首先从原始数组创建一个新的一维数组。

$arr = array("key1"=>"value1","key2"=>"value2","key3"=>"value3");

foreach ($arr as $row)  $vector[] = $row['key1'];

in_array($needle,$vector);

It works too creating first a new unidimensional Array from the original one.

$arr = array("key1"=>"value1","key2"=>"value2","key3"=>"value3");

foreach ($arr as $row)  $vector[] = $row['key1'];

in_array($needle,$vector);
请恋爱 2024-10-08 01:57:25

较短的版本,用于基于数据库结果集创建的多维数组。

function in_array_r($array, $field, $find){
    foreach($array as $item){
        if($item[$field] == $find) return true;
    }
    return false;
}

$is_found = in_array_r($os_list, 'os_version', 'XP');

如果 $os_list 数组的 os_version 字段中包含“XP”,则返回。

Shorter version, for multidimensional arrays created based on database result sets.

function in_array_r($array, $field, $find){
    foreach($array as $item){
        if($item[$field] == $find) return true;
    }
    return false;
}

$is_found = in_array_r($os_list, 'os_version', 'XP');

Will return if the $os_list array contains 'XP' in the os_version field.

诗化ㄋ丶相逢 2024-10-08 01:57:25

array_search 怎么样?根据 https://gist.github.com/Ocramius/1290076 ,它似乎比 foreach 快得多..

if( array_search("Irix", $a) === true) 
{
    echo "Got Irix";
}

what about array_search? seems it quite faster than foreach according to https://gist.github.com/Ocramius/1290076 ..

if( array_search("Irix", $a) === true) 
{
    echo "Got Irix";
}
千寻… 2024-10-08 01:57:25

我发现了非常小的简单解决方案:

如果你的数组是:

Array
(
[details] => Array
    (
        [name] => Dhruv
        [salary] => 5000
    )

[score] => Array
    (
        [ssc] => 70
        [diploma] => 90
        [degree] => 70
    )

)

那么代码将是这样的:

 if(in_array("5000",$array['details'])){
             echo "yes found.";
         }
     else {
             echo "no not found";
          }

I found really small simple solution:

If your array is :

Array
(
[details] => Array
    (
        [name] => Dhruv
        [salary] => 5000
    )

[score] => Array
    (
        [ssc] => 70
        [diploma] => 90
        [degree] => 70
    )

)

then the code will be like:

 if(in_array("5000",$array['details'])){
             echo "yes found.";
         }
     else {
             echo "no not found";
          }
逆流 2024-10-08 01:57:25

我发现以下解决方案代码不是很干净,但它有效。它用作递归函数。

function in_array_multi( $needle, $array, $strict = false ) {
  foreach( $array as $value ) { // Loop thorugh all values
    // Check if value is aswell an array
    if( is_array( $value )) {
      // Recursive use of this function
      if(in_array_multi( $needle, $value )) {
        return true; // Break loop and return true
      }
    } else {
      // Check if value is equal to needle
      if( $strict === true ) {
        if(strtolower($value) === strtolower($needle)) {
          return true; // Break loop and return true
        }
      }else {
        if(strtolower($value) == strtolower($needle)) {
          return true; // Break loop and return true
        }
      }
    }
  }

  return false; // Nothing found, false
}

I have found the following solution not very clean code but it works. It is used as an recursive function.

function in_array_multi( $needle, $array, $strict = false ) {
  foreach( $array as $value ) { // Loop thorugh all values
    // Check if value is aswell an array
    if( is_array( $value )) {
      // Recursive use of this function
      if(in_array_multi( $needle, $value )) {
        return true; // Break loop and return true
      }
    } else {
      // Check if value is equal to needle
      if( $strict === true ) {
        if(strtolower($value) === strtolower($needle)) {
          return true; // Break loop and return true
        }
      }else {
        if(strtolower($value) == strtolower($needle)) {
          return true; // Break loop and return true
        }
      }
    }
  }

  return false; // Nothing found, false
}
帅哥哥的热头脑 2024-10-08 01:57:25

许多这样的搜索通常是为了在记录列表中查找内容,正如一些人指出的那样,这实际上是一个二维数组。

这是针对具有统一键集的记录列表,例如从数据库中抓取的记录列表等。

为了完整性,该结构包含“in_array”和“key_exists”样式的函数。这两个函数都返回一个简单的真/假布尔答案。

二维记录数组示例...

$records array:

  [0] => Array
    (
        [first_name] => Charlie
        [last_name] => Brown
    )
  [1] => Array
    (
        [first_name] => Fred
        [last_name] => Sanford
    )

功能:

function in_multidimensional_array($array, $column_key, $search) { 
   return in_array($search, array_column($array, $column_key)); 
}

function multidimensional_array_key_exists($array, $column_key) { 
   return in_array($column_key, array_keys(array_shift($array))); 
}

测试:

var_dump(in_multidimensional_array($records, 'first_name', 'Charlie')); // true

var_dump(multidimensional_array_key_exists($records, 'first_name')); // true

Many of these searches are usually for finding things in a list of records, as some people have pointed out is really a 2-dimensional array.

This is for a list of records that have a uniform set of keys) such as a list of records grabbed from a database, among other things.

Included are both 'in_array' and 'key_exists' styled functions for this structure for completeness. Both functions return a simple true/false boolean answer.

Example 2-dimensional array of records...

$records array:

  [0] => Array
    (
        [first_name] => Charlie
        [last_name] => Brown
    )
  [1] => Array
    (
        [first_name] => Fred
        [last_name] => Sanford
    )

Functions:

function in_multidimensional_array($array, $column_key, $search) { 
   return in_array($search, array_column($array, $column_key)); 
}

function multidimensional_array_key_exists($array, $column_key) { 
   return in_array($column_key, array_keys(array_shift($array))); 
}

Tests:

var_dump(in_multidimensional_array($records, 'first_name', 'Charlie')); // true

var_dump(multidimensional_array_key_exists($records, 'first_name')); // true
伏妖词 2024-10-08 01:57:25

你可以这样使用

$result = array_intersect($array1, $array2);
print_r($result);

http://php.net/manual/tr/function .array-intersect.php

you can use like this

$result = array_intersect($array1, $array2);
print_r($result);

http://php.net/manual/tr/function.array-intersect.php

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