按值获取数组中元素的索引

php
2022-08-30 15:10:44

我在PHP中有这个数组:

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

如果我有“用户名”字符串,如何获取索引值作为数字?

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


答案 1

看看array_search

从 PHP 帮助文件中:

<?php
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');

$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array);   // $key = 1;
?>

答案 2

如果您有一个 2D 数组(如示例中所示),则需要稍微自定义一些内容:

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;
}

如果您只想在一个特定字段中进行搜索,则可以将函数更改为如下所示:

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

推荐