繁体   English   中英

获取数组中某个值在PHP中的索引

[英]Get the index of a certain value in an array in PHP

我有一个数组:

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

我想获取给定值的索引(即string21string32

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

  • 字符串 1 为 0
  • 字符串 2 为 1
  • 字符串 3 是 2

如何做到这一点?

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;

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

如果您只执行其中的几个(和/或数组大小很大),那么您就在使用 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, "

其他人建议使用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 = 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

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

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

能不能具体一点?

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

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

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

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

尝试 array_keys PHP 函数。

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

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

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

对于正在寻找的人:如何通过数组的键和值查找索引。 这个可能会有帮助!

function findIndexByKeyValue($arraytosearch, $key, $valuetosearch) {

    for ($i = 0; $i < count($arraytosearch); $i++) {

        if ($arraytosearch[$i][$key] == $valuetosearch) {
            return $i;
        }
    }
    return null;
}

它被称为这样的:

$index = findIndexByKeyValue($array, "key", $value);

这是一个适用于数字或字符串索引的函数。 将数组作为第一个参数传递,然后将索引传递给需要移动的元素,最后将方向设置为 -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;

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM