在PHP中获取数组的索引值

时间:2010-06-02 15:38:27

标签: php arrays

我有一个数组:

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

我想获取给定值的索引(即1的{​​{1}}和string2的{​​{1}}

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

  • string1为0
  • string2是1
  • string3是2

如何实现这一目标?

12 个答案:

答案 0 :(得分:119)

array_search是这样做的方法。

  

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

来自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;

你可以手动循环遍历数组并找到索引,但为什么在有这个功能的时候会这样做。此函数始终返回一个键,它可以很好地处理关联和普通数组。

答案 1 :(得分:15)

如果你只做了一些(和/或数组大小很大),那么你使用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, "

答案 2 :(得分:8)

其他人建议使用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()没用。你能解释一下原因吗?你尝试了什么,它是如何不符合你的需求的?

答案 3 :(得分:8)

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

$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

答案 4 :(得分:5)

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

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

答案 5 :(得分:1)

尝试使用array_keys PHP函数。

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

答案 6 :(得分:1)

你能更具体一点吗?

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

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

答案 7 :(得分: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));

答案 8 :(得分: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));

答案 9 :(得分: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;

答案 10 :(得分:0)

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

答案 11 :(得分:-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;

}

相关问题