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

rof*_*fle 28 php

我在PHP中有这个数组:

array(
    [0] => array( 'username' => 'user1' )
    [1] => array( 'username' => 'user2' )
)
Run Code Online (Sandbox Code Playgroud)

如果我有"用户名"字符串,我怎样才能将索引值作为数字?

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

Dan*_*ker 28

看一下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;
?>
Run Code Online (Sandbox Code Playgroud)

  • 这对他不起作用,因为他有一个2D阵列.虽然......奇怪的是,它被接受了. (2认同)

nic*_*ckf 25

如果您有一个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;
}
Run Code Online (Sandbox Code Playgroud)

如果您只想搜索一个特定字段,可以将函数更改为以下内容:

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

  • 而不是使用for/count循环循环数组 - 为什么不"foreach($ haystack as $ key => $ value)" - 而且,这将在任何字段中找到'user1',而不仅仅是"username" (2认同)

Sha*_*lin 7

这很简单

private function getArrayKey($haystack, $needle)
{
  foreach($haystack as $key => $product)
  {
     if ($product['id'] === $needle)
     return $key;
  }

  return false;
}
Run Code Online (Sandbox Code Playgroud)