获取与多维数组中的值匹配的元素 [英] Get element that matches value in multi-dimensional array

查看:50
本文介绍了获取与多维数组中的值匹配的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个多维数组。

我想获取数组中与某个值匹配的元素。

I want to get the element in the array that matches a certain value.

Array:

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

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

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

获取数组元素的代码,其中 id = 2

Code to get array element where id = 2:

$key = array_search(2, array_column($userDB, 'id'));

当前代码未返回任何内容。

Current code is not returning anything.

推荐答案

您可以循环遍历数组,并在找到符合条件的元素时停止。

You can just loop over the array, and when you find the element that meets your criteria, stop.

$id = 2;
$found_user = null;
foreach ($userdb as $user) {
    if ($user['id'] == $id) {
        $found_user = $user;
        break;
    }
}

使用您当前的代码, $ key 应该设置为 2 ,但是请记住,变量名区分大小写,(所以 $ userdb!= $ userDB )。如果您只想获取密钥,则只要您使用正确的变量名,它就应该起作用。如果要获取整个元素,则可以直接使用array_search返回的键:

With your current code, $key should be set to 2, but remember that variable names are case sensitive, (so $userdb != $userDB). If you just want to get the key, it should work as long as you are using the correct variable name. If you want to get the entire element, then you can use the key returned by array_search directly:

$user = $userdb[array_search(2, array_column($userdb, 'id'))];

这篇关于获取与多维数组中的值匹配的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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