Php in_array()和多维数组
我在数组()中使用Php in_array()和多维数组,php,arrays,multidimensional-array,Php,Arrays,Multidimensional 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); 或者,当涉及多维数组
,
检查数组中是否存在值,如下所示
$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);
或者,当涉及多维数组时,我不应该在数组()中使用,
。这样就可以了:
foreach($b as $value)
{
if(in_array("Irix", $value, true))
{
echo "Got Irix";
}
}
in_array
仅在一维数组上运行,因此需要在每个子数组上循环并在每个子数组上运行in_array
正如其他人所指出的,这仅适用于二维数组。如果有更多嵌套数组,则递归版本会更好。请参阅其他答案以获取示例。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';
if(in_array_r($item , $array)){
// found!
}
这是我在中找到的第一个此类函数。注释部分中的函数并不总是最好的,但如果它不起作用,您也可以在那里查看:)
功能非常好,但直到我将
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;
}
如果你的数组像这样
$array = array(
array("name" => "Robert", "Age" => "22", "Place" => "TN"),
array("name" => "Henry", "Age" => "21", "Place" => "TVL")
);
$result = array_intersect($array1, $array2);
print_r($result);
用这个
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;
}
_multiarray($elem,$array,$field)中的函数
{
$top=sizeof($array)-1;
$bottom=0;
而($bottom请尝试:
in_array("irix",array_keys($b))
in_array("Linux",array_keys($b["irix"])
我不确定是否需要,但这可能符合您的要求它也可以先从原始阵列创建一个新的一维阵列
$arr = array("key1"=>"value1","key2"=>"value2","key3"=>"value3");
foreach ($arr as $row) $vector[] = $row['key1'];
in_array($needle,$vector);
您始终可以序列化多维数组并执行以下操作:
$arr = array(array("Mac", "NT"), array("Irix", "Linux"));
$in_arr = (bool)strpos(serialize($arr),'s:4:"Irix";');
if($in_arr){
echo "Got Irix!";
}
我使用的各种文档:
- 这也会起作用
function in_array_r($item , $array){
return preg_match('/"'.preg_quote($item, '/').'"/i' , json_encode($array));
}
用法:
$b = array(array("Mac", "NT"), array("Irix", "Linux"));
echo in_array_r("Irix", $b) ? 'found' : 'not found';
if(in_array_r($item , $array)){
// found!
}
较短的版本,用于基于数据库结果集创建的多维数组
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_列表数组在os_版本字段中包含“XP”,则将返回。关于数组搜索的情况如何?根据
如果知道要搜索的列,可以使用array\u search()和array\u column() 这一想法在PHP手册的数组搜索()注释部分;以下是我基于json编码()解决方案的建议:
$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';
}
- 不区分大小写选项
- 返回计数而不是true
- 数组中的任意位置(键和值)
希望对您有所帮助。我相信您现在可以使用:
<?php
$a=array("Mac"=>"NT","Irix"=>"Linux");
if (array_key_exists("Mac",$a))
{
echo "Key exists!";
}
else
{
echo "Key does not exist!";
}
?>
我正在寻找一个函数,它可以让我在数组(haystack)中同时搜索字符串和数组,因此我添加了一个函数 这是我的密码:
/**
* 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;
}
你可以这样用
$array = array(
array("name" => "Robert", "Age" => "22", "Place" => "TN"),
array("name" => "Henry", "Age" => "21", "Place" => "TVL")
);
$result = array_intersect($array1, $array2);
print_r($result);
作者
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
及
计算true
,因为“示例”
被强制转换为int
,并转换为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;
}
对于多维子项:
在数组('needle',array\u列($arr,'key'))中
对于一维子对象:在_数组('needle',call_user_func_数组('array_merge',$arr))
我找到了非常简单的解决方案:
如果您的阵列是:
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";
}
我使用这种方法对任何数量的嵌套对象都有效,不需要黑客攻击
<?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;
}
}
由于PHP5.6有一个更好、更干净的原始答案解决方案:
使用如下多维数组:
$a=数组(数组(“Mac”、“NT”)、数组(“Irix”、“Linux”))
我们可以使用:
在数组中返回(“Irix”,数组合并(…$a),true)
如果您有如下字符串键:
$a=array(“a”=>array(“Mac”、“NT”),“b”=>array(“Irix”、“Linux”))
您必须使用数组\u值
以避免错误无法使用字符串键解压数组
:
在数组中返回(“Irix”,数组合并(…数组值($a)),true)
我发现下面的解决方案不是很干净的代码,但它可以工作。它被用作递归函数
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
}
但是,这只能在一维中工作。为了检查每个深度,您必须创建一个递归函数。我运行了代码,但它有一个错误-解析错误:第21行的C:\wamp\www\000\u TEST\php\php.in\u array\index.php中的解析错误-这是if(in\u array(“Irix”),$value),谢谢。@lauthiamkok:有一个)
前面提到的行的末尾缺少。谢谢,我修正了我的答案。当我打字太快并且不重读我的代码时就会发生这种情况。你应该总是在_array()中调用
将第三个参数设置为true
。请查看此处原因:难以捉摸的解决方案更好,因为它只适用于阵列谢谢。该函数非常优雅!喜欢它!谢谢。我怎么知道它返回true或false,因为我在运行函数时屏幕上没有显示任何内容?谢谢。我正在寻找这样做的东西,您只需保存即可我写了我自己的:)它工作得很好。那么我们如何搜索和显示数组键呢?例如:$b=array(1=>array(“Mac”,“NT”),3=>array(“Irix”,“Linux”);@d.Tate StackOverflow上的代码根据需要的属性获得许可(见页脚)。您只需包含一条与此答案永久链接的注释即可。@B:这是非常有意的。这就是函数递归的原因(例如,\u r
,类似于print\u r()
),它会下降到所有嵌套数组中进行搜索
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
}