php 通过值获取数组中元素的索引
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/855553/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get index of element in an array by the value
提问by roflwaffle
I have this array in PHP:
我在 PHP 中有这个数组:
array(
[0] => array( 'username' => 'user1' )
[1] => array( 'username' => 'user2' )
)
If I have the 'username' string how can I get the index value as a number?
如果我有“用户名”字符串,我怎样才能以数字形式获取索引值?
Example, if I have 'user1' how can I get 0?
例如,如果我有“user1”,我怎么能得到 0?
采纳答案by nickf
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;
}
回答by Dan Walker
Take a look at array_search.
看看array_search。
From the PHP help file:
从 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;
?>
回答by Shaolin
This would be very simple
这将非常简单
private function getArrayKey($haystack, $needle)
{
foreach($haystack as $key => $product)
{
if ($product['id'] === $needle)
return $key;
}
return false;
}
回答by AbraCadaver
If you know that the key is username, just use an array as the search parameter:
如果您知道键是username,只需使用数组作为搜索参数:
$username = 'user1';
$key = array_search(array('username' => $username), $array);
回答by gnarf
Perhaps using array_filterand array_keystogether will help.
也许使用array_filter和array_keys一起使用会有所帮助。
Class Based Approach.
基于类的方法。
<?php
class ArraySearch2d {
static protected $_key;
static protected $_value;
static function isMatch($element)
{
if (!is_array($element)) return false;
return $element[self::$_key] == self::$_value;
}
static function filter(array $arrayToSearch, $key, $value)
{
if (!is_string($key)) throw new Exception("Array Key must be a string");
self::$_key = $key;
self::$_value = $value;
return array_filter($arrayToSearch, 'ArraySearch2d::isMatch');
}
// to directly answer your question.
static function getIndex(array $arrayToSearch, $key, $value)
{
$matches = self::filter($arrayToSearch, $key, $value);
if (!count($matches)) return false;
$indexes = array_keys($matches);
return $indexes[0];
}
}
$array = array("1"=>array('username'=>'user1'), "3"=>array('username'=>'user2'));
$matches = ArraySearch2d::filter($array, 'username', 'user2');
var_dump($matches);
$indexs = array_keys($matches);
var_dump($indexs);
// Demonstrating quick answer:
echo "Key for first 'username'=>'user1' element is: "
.ArraySearch2d::getIndex($array, 'username', 'user1')."\n";
Produces:
产生:
array(1) {
[3]=>
array(1) {
["username"]=>
string(5) "user2"
}
}
array(1) {
[0]=>
int(3)
}
Key for first 'username'=>'user1' element is: 1
Without using classes - this produces the same result:
不使用类 - 这会产生相同的结果:
<?php
$field="username";
$value = "user2";
function usernameMatch($element)
{
global $field, $value;
if (!is_array($element)) return false;
return $element[$field] == $value;
}
function getFirstIndex(array $array)
{
if (!count($array)) return false;
$indexes = array_keys($array);
return $indexes[0];
}
$array = array("1"=>array('username'=>'user1'), "3"=>array('username'=>'user2'));
$matches = array_filter($array, 'usernameMatch');
var_dump($matches);
$indexs = array_keys($matches);
var_dump($indexs);
// Demonstrating quick answer - and why you should probably use the class-
// you don't want to have to remember these "globals" all the time.
$field = 'username';
$value = 'user1';
echo "Key for first 'username'=>'user1' element is: "
.getFirstIndex(array_filter($array, 'usernameMatch'));

