Jump to content
  • Hello visitors, welcome to the Hacker World Forum!

    Red Team 1949  (formerly CHT Attack and Defense Team) In this rapidly changing Internet era, we maintain our original intention and create the best community to jointly exchange network technologies. You can obtain hacker attack and defense skills and knowledge in the forum, or you can join our Telegram communication group to discuss and communicate in real time. All kinds of advertisements are prohibited in the forum. Please register as a registered user to check our usage and privacy policy. Thank you for your cooperation.

    TheHackerWorld Official

php判断多维数组中是否含有某个值

 Share


Recommended Posts

在php开发中,我们有时候需要检查PHP多维数组中是否存在某一值Value。在本教程中,我们将演示并描述了如何检查多维数组中是否存在某一值的几种方法。我们将使用以下2种方法来做到这一点。

  1. PHP in_array()和array_column()函数
  2. 自定义函数

 

PHP in_array()和array_column()函数

php in_array()检查数组中是否存在某个值,只是这个方法不能检查多维数组。但是我们可以使用in_array()和array_column()函数检查多维数组中是否存在Value。

例子:

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


if(in_array(100, array_column($userdb, 'uid'))) { // search value in the array
    echo "FOUND";
}
?>

array_column() 返回输入数组中某个单一列的值.

array_column($userdb, 'uid')

它将返回如下数组:

Array
(
  [0] => 100
  [1] => 5465
  [2] => 40489
)

然后我们使用in_array()函数检查一维数组中是否存在值"100"。

 

自定义函数

我们可以使用类似下面的递归方法来检查多维数组中是否存在某一值。

function deep_in_array($value, $array) {   
        foreach($array as $item) {   
            if(!is_array($item)) {   
                if ($item == $value) {  
                    return true;  
                } else {  
                    continue;
                }  
            }   
                
            if(in_array($value, $item)) {  
                return true;      
            } else if(deep_in_array($value, $item)) {  
                return true;      
            }  
        }   
        return false;   
    }
 
以上就是本文的全部内容,希望对大家的学习有所帮助。更多教程请访问码农之家
Link to post
Link to comment
Share on other sites

 Share

discussion group

discussion group

    You don't have permission to chat.
    • Recently Browsing   0 members

      • No registered users viewing this page.
    ×
    ×
    • Create New...