获取PHP中数组的索引值


86

我有一个数组:

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

我想要得到的指数给定值(即1用于string22string3

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

  • 字符串1为0
  • string2是1
  • string3是2

如何实现呢?


7
我的一位技术作家朋友告诉我:“除非您提出正确的问题,否则您将无法获得正确的答案。”
Bill Karwin 2010年

这是旧的....但是我很想知道为什么:“我尝试了array_search但没有用”
dsdsdsdsd 2014年

请将较高评分的答案标记为已接受。
罗布施(Robsch)2015年

如果您像我一样有一个关联数组,此答案会有所帮助:stackoverflow.com/a/3365793/470749
Ryan

Answers:


157

array_search 是这样做的方法。

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

文档

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

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

您可以手动遍历数组并找到索引,但是为什么要在有此功能的情况下这样做呢?此函数始终返回键,并且将与关联数组和普通数组一起使用。


10
这将返回键,而不是索引。在您的示例中,键很方便地是值的索引。
豪尔赫·费雷拉

1
@ smink,OP的数组是非关联数组,因此可以正常工作。
马修·弗拉申(Martin Flaschen)2010年

抱歉,我没有指定数组的类型。我使用的数组是多维数组,请参阅我的解决方案答案
Aakash Chakravarthy

我有这种类型的数组:[0 => {id:1,name:something},1 => {.....},...]。这有可能找到像array_search(“ name” => something,$ array)这样的键/索引吗?
lazzy_ms

数组中是否有孩子呢?
zukijuki

19

如果仅执行其中的一些操作(和/或数组大小很大),则使用array_search的方向正确:

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

如果您想要全部(或其中很多),则循环可能使您更好:

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

1
foreach是我所需要的
zzapper 2014年

11

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

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

// result: 1

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


“ array_values()没用” ..应该是“ array_search()没用”
Vex 2010年

7

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

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

//您可以

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

//执行

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

//或者

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

//递归地

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

//输出

//-- 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

6

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

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

这是迄今为止该问题最短且
可行的

1

您能具体一点吗?

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

对我来说很好。您是否正在尝试完成更复杂的事情?


1

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

 $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));

1
该问题未提及多维数组(OP在其他答案中的评论表明该答案是他实际上正在寻找的答案,但是如果您仅阅读原始问题和此答案,则您说的是没有意义的)
StubbornShowaGuy

1

您必须为此创建一个函数。我认为没有任何内置功能可用于此目的。默认情况下,所有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



0

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

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

$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));

0
$find="Topsite";
$list=array("Tope","Ajayi","Topsite","Infotech");
$list_count=count($list);
sort($list);
for($i=0;$i<$list_count;$i++)
{
    if($list[$i]==$find){
         $position=$i;
    }

}
echo $position;

-1

这是一个适用于数字或字符串索引的函数。将数组作为第一个参数传递,然后传递给需要移动的元素的索引,最后将方向设置为-1以将元素向上移动,将方向设置为1以将元素向下移动。例如:Move(['first'=>'Peter','second'=>'Paul','third'=>'Kate'],'second',-1)将使Paul向上移动,而Peter向下移动。

function Move($a,$element,$direction)
{

$temp = [];
$index = 0;

foreach($a as $key=>$value)
{
    $temp[$index++] = $key;
}

$index = array_search($element,$temp);

$newpos = $index+$direction;

if(isset($temp[$newpos]))
{
        $value2 = $temp[$newpos];
        $temp[$newpos]=$element;
        $temp[$index]=$value2;
}
else
{
    # move is not possible
    return $a; # returns the array unchanged
}   

$final = [];

foreach($temp as $next)
{
    $final[$next]=$a[$next];
}

return $final;

}

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.