PHP 获取数组的索引值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2959222/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 08:15:02  来源:igfitidea点击:

Get the index value of an array in PHP

phparrays

提问by Aakash Chakravarthy

I have an array:

我有一个数组:

$list = array('string1', 'string2', 'string3');

I want to get the index for a given value (i.e. 1for string2and 2for string3)

我想获取给定值的索引(即1forstring22for string3

All I want is the position of the strings in the array

我想要的只是字符串在数组中的位置

  • string1 is 0
  • string2 is 1
  • string3 is 2
  • 字符串 1 为 0
  • 字符串 2 是 1
  • 字符串 3 是 2

How to achieve this?

如何实现这一目标?

回答by RaYell

array_searchis the way to do it.

array_search是这样做的方法。

array_search ( mixed $needle , array $haystack [, bool $strict = FALSE ] ) : mixed

array_search ( mixed $needle , array $haystack [, bool $strict = FALSE ] ) : mixed

From the docs:

文档

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

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

You could loop over the array manually and find the index but why do it when there's a function for that. This function always returns a key and it will work well with associative and normal arrays.

您可以手动遍历数组并找到索引,但是当有一个函数时为什么要这样做。这个函数总是返回一个键,它可以很好地处理关联数组和普通数组。

回答by ircmaxell

If you're only doing a few of them (and/or the array size is large), then you were on the right track with array_search:

如果您只执行其中的几个(和/或数组大小很大),那么您就在使用 array_search 的正确轨道上:

$list = array('string1', 'string2', 'string3');
$k = array_search('string2', $list); //$k = 1;

If you want all (or a lot of them), a loop will prob do you better:

如果你想要全部(或很多),循环会更好:

foreach ($list as $key => $value) {
    echo $value . " in " . $key . ", ";
}
// Prints "string1 in 0, string2 in 1, string3 in 2, "

回答by Bill Karwin

Other folks have suggested array_search()which gives the key of the array element where the value is found. You can ensure that the array keys are contiguous integers by using array_values():

其他人建议array_search()给出找到值的数组元素的键。您可以使用以下方法确保数组键是连续的整数array_values()

$list = array(0=>'string1', 'foo'=>'string2', 42=>'string3');
$index = array_search('string2', array_values($list));
print "$index\n";

// result: 1

You said in your question that array_search()was no use. Can you explain why? What did you try and how did it not meet your needs?

你在你的问题中说array_search()没有用。你能解释一下为什么吗?您尝试了什么,它如何不满足您的需求?

回答by Michael Hurley

// or considering your array structure:

// 或考虑您的数组结构:

$array = array(
  'string1' => array('a' => '', 'b' => '', 'c' => ''),
  'string2' => array('a' => '', 'b' => '', 'c' => ''),
  'string3' => array('a' => '', 'b' => '', 'c' => ''),
);

// you could just

// 你可以

function findIndexOfKey($key_to_index,$array){
  return array_search($key_to_index,array_keys($array));
}

// executed

// 执行

print "\r\n//-- Method 1 --//\r\n";
print '#index of: string1 = '.findIndexofKey('string1',$array)."\r\n";
print '#index of: string2 = '.findIndexofKey('string2',$array)."\r\n";
print '#index of: string3 = '.findIndexofKey('string3',$array)."\r\n";

// alternatively

// 或者

print "\r\n//-- Method 2 --//\r\n";
print '#index of: string1 = '.array_search('string1',array_keys($array))."\r\n";
print '#index of: string2 = '.array_search('string2',array_keys($array))."\r\n";
print '#index of: string3 = '.array_search('string3',array_keys($array))."\r\n";

// recursersively

// 递归

print "\r\n//-- Method 3 --//\r\n";
foreach(array_keys($array) as $key => $value){
  print '#index of: '.$value.' = '.$key."\r\n";
}

// outputs

// 输出

//-- Method 1 --//
#index of: string1 = 0
#index of: string2 = 1
#index of: string3 = 2

//-- Method 2 --//
#index of: string1 = 0
#index of: string2 = 1
#index of: string3 = 2

//-- Method 3 --//
#index of: string1 = 0
#index of: string2 = 1
#index of: string3 = 2

回答by Brian Berneker

The problem is that you don't have a numerical index on your array.
Using array_values() will create a zero indexed array that you can then search using array_search() bypassing the need to use a for loop.

问题是您的数组上没有数字索引。
使用 array_values() 将创建一个零索引数组,然后您可以使用 array_search() 进行搜索,而无需使用 for 循环。

$list = array('string1', 'string2', 'string3');
$index = array_search('string2',array_values($list));

回答by Krish PG

You'll have to create a function for this. I don't think there is any built-in function for that purpose. All PHP arrays are associative by default. So, if you are unsure about their keys, here is the code:

您必须为此创建一个函数。我不认为有任何为此目的的内置功能。默认情况下,所有 PHP 数组都是关联的。所以,如果你不确定他们的密钥,这里是代码:

<?php

$given_array = array('Monday' => 'boring',
'Friday' => 'yay',
'boring',
'Sunday' => 'fun',
7 => 'boring',
'Saturday' => 'yay fun',
'Wednesday' => 'boring',
'my life' => 'boring');

$repeating_value = "boring";

function array_value_positions($array, $value){
    $index = 0;
    $value_array = array();
        foreach($array as $v){
            if($value == $v){
                $value_array[$index] = $value;
            }
        $index++;
        }
    return $value_array;
}

$value_array = array_value_positions($given_array, $repeating_value);

$result = "The value '$value_array[0]' was found at these indices in the given array: ";

$key_string = implode(', ',array_keys($value_array));

echo $result . $key_string . "\n";//Output: The value 'boring' was found at these indices in the given array: 0, 2, 4, 6, 7

回答by Vex

This code should do the same as your new routine, working with the correct multi-dimensional array..

此代码应该与您的新例程相同,使用正确的多维数组。

 $arr = array(
  'string1' => array('a' => '', 'b' => '', 'c' => ''),
  'string2' => array('a' => '', 'b' => '', 'c' => ''),
  'string3' => array('a' => '', 'b' => '', 'c' => '')
 );

 echo 'Index of "string2" = '. array_search('string2', array_keys($arr));

回答by Jeff

Could you be a little more specific?

能不能具体一点?

$key = array_search('string2',$list)

works fine for me. Are you trying to accomplish something more complex?

对我来说很好用。你想完成更复杂的事情吗?

回答by Evernoob

Try the array_keys PHP function.

尝试 array_keys PHP 函数。

$key_string1 = array_keys($list, 'string1');

回答by Vex

array_search should work fine, just tested this and it returns the keys as expected:

array_search 应该可以正常工作,只是测试了它并按预期返回键:

$list = array('string1', 'string2', 'string3');
echo "Key = ".array_search('string1', $list);
echo " Key = ".array_search('string2', $list);
echo " Key = ".array_search('string3', $list);

Or for the index, you could use

或者对于索引,您可以使用

$list = array('string1', 'string2', 'string3');
echo "Index = ".array_search('string1', array_merge($list));
echo " Index = ".array_search('string2', array_merge($list));
echo " Index = ".array_search('string3', array_merge($list));