【问题标题】:Get the index of a certain value in an array in PHPPHP中获取数组中某个值的索引
【发布时间】:2011-02-26 21:40:40
【问题描述】:

我有一个数组:

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

我想获取给定值的索引(例如,1 对应 string22 对应 string3

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

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

如何做到这一点?

【问题讨论】:

  • 我的一位科技作家朋友告诉我:“除非你提出正确的问题,否则你无法得到正确的答案。”
  • 这是旧的......但我想知道为什么:“我试过 array_search 但没用”
  • 请将评分较高的答案标记为已接受。
  • 如果你有一个关联数组,就像我一样,这个答案会有所帮助:stackoverflow.com/a/3365793/470749

标签: php arrays


【解决方案1】:

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;

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

【讨论】:

  • 这将返回键,而不是索引。在您的示例中,键很方便地是值的索引。
  • @smink,OP的数组是一个非关联数组,所以可以正常工作。
  • 对不起,我没有指定数组的类型。我使用的数组是多维数组,解决方法请看我的回答
  • 我有这种类型的数组:[ 0 => { id : 1, name : something}, 1 => {.....}, ...]。这可以找到像 array_search("name"=>something,$array) 这样的键/索引吗?
  • 如果数组有子呢?
【解决方案2】:

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

【讨论】:

  • foreach 是我需要的
【解决方案3】:

其他人建议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() 没用”
【解决方案4】:

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

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

【讨论】:

  • 这是迄今为止解决问题的最短且有效的方法,
【解决方案5】:

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

$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_keys PHP 函数。

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

    【讨论】:

    • 那些参数不是reversed吗?
    • @ashleedawg 不,你看错了,array_keysarray_search 不同
    【解决方案7】:

    你能说得更具体一点吗?

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

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

    【讨论】:

      【解决方案8】:

      这段代码应该和你的新例程一样,使用正确的多维数组..

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

      【讨论】:

      • 这个问题没有提到多维数组(OP 在其他答案中的 cmets 表明这个答案是他真正想要的,但如果你只阅读原始问题和这个答案,你说的没有道理)
      【解决方案9】:

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

      【讨论】:

        【解决方案10】:
        $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;
        

        【讨论】:

          【解决方案11】:

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

          【讨论】:

            【解决方案12】:

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

            }

            【讨论】:

              猜你喜欢
              • 2017-11-08
              • 2013-02-08
              • 1970-01-01
              • 2016-02-03
              • 1970-01-01
              • 2022-01-13
              • 2016-03-20
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多