通过值获取数组中元素的索引 [英] Get index of element in an array by the value

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

问题描述

我在PHP中有这个数组:

I have this array in PHP:

array(
    [0] => array( 'username' => 'user1' )
    [1] => array( 'username' => 'user2' )
)

如果我有'username'字符串,如何获取索引值作为数字?

If I have the 'username' string how can I get the index value as a number?

例如,如果我有'user1',我怎么能得到0?

Example, if I have 'user1' how can I get 0?

推荐答案

如果您有一个2D数组(如您的示例中所示),则需要进行一些自定义:

If you have a 2D array, like in your example, you'll need to customise things a little:

function array_search2d($needle, $haystack) {
    for ($i = 0, $l = count($haystack); $i < $l; ++$i) {
        if (in_array($needle, $haystack[$i])) return $i;
    }
    return false;
}

$myArray = array(
    array( 'username' => 'user1' ),
    array( 'username' => 'user2' )
);
$searchTerm = "user1";

if (false !== ($pos = array_search2d($searchTerm, $myArray))) {
    echo $searchTerm . " found at index " . $pos;
} else {
    echo "Could not find " . $searchTerm;
}

如果您只想在一个特定的字段中进行搜索,则可以将功能更改为以下形式:

If you wanted to search in just one particular field, you could alter the function to something like this:

function array_search2d_by_field($needle, $haystack, $field) {
    foreach ($haystack as $index => $innerArray) {
        if (isset($innerArray[$field]) && $innerArray[$field] === $needle) {
            return $index;
        }
    }
    return false;
}

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

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