使用array_search和array_column不返回Array [0]的值来检查多维数组中是否存在值 [英] Check if value exists in multidimensional array using array_search and array_column not returning values of Array[0]

查看:263
本文介绍了使用array_search和array_column不返回Array [0]的值来检查多维数组中是否存在值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要检查多维数组中是否存在值.我在 Stackoverflow 和上找到了这个示例我喜欢 PHP.NET ,因为它是一种优雅而紧凑的解决方案,但是我注意到了一个奇怪的行为:

I need to check if a value exists in a multidimensional array. I found this example on Stackoverflow and on PHP.NET which I like because its an elegant and compact solution, but I noticed a weird behavior:

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

(1) => Array
    (
        (uid) => '5465',
        (name) => 'Stefanie Mcmohn',
        (pic_square) => 'urlof100'
    ),

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



if(array_search(100, array_column($userdb, 'uid'))) {
    echo "FOUND";
}

如果您检查 FIRST 数组(Array [0])是否存在任何值,IF语句将不返回任何值.它确实可以与其他数组的值一起使用.先尝试使用100,然后尝试使用40489(或尝试使用名称"或"pic_square").

The IF statement does not return any value if you check the existence of any value of the FIRST array (Array [0]). It does work with the values of the other arrays. Try with 100 first, then try with 40489 (or try with a "name" or "pic_square").

推荐答案

您可以像下面这样使用in_array():-

You can use in_array() like below:-

<?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'
    )
);
print_r(array_column($userdb, 'uid')); 
if(in_array(100, array_column($userdb, 'uid'))) { // search value in the array
    echo "FOUND";
}
?>

输出:- https://eval.in/1058147

注意:-如果您修改如下所示的比较,您的代码也将起作用:-

Note:- you code will work also if you modify your comparison like below:-

if(array_search(100, array_column($userdb, 'uid')) !== false) {
    echo "FOUND";
} else {
    echo "Not Found";
}

通过手册:- http://php.net/manual/zh /function.array-search.php

它满足:-

如果在阵列中找到了针,则返回针的键,否则返回FALSE.

php0视为false,将1视为true.这就是您的代码失败的原因,因为您的代码返回0(与在数组的第一个索引上找到的匹配项一样).

php treated 0 as false and 1 as true. That's why your code fails, because your code returns 0 (as match found on the very first index of array).

这篇关于使用array_search和array_column不返回Array [0]的值来检查多维数组中是否存在值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆