【问题标题】:how to search array by specifying the index to start search from in php如何通过指定索引在php中开始搜索来搜索数组
【发布时间】:2018-04-30 10:30:19
【问题描述】:

如何在 php 中通过指定索引开始搜索来搜索数组

例如: 假设

$needle_to_search = 5;
$array_to_search = [6,8,4,9,7,5,9,4,5,9,3,5,4,6,7];
$index_to_start_search_from = 5;
$key = array_search($needle_to_search, $array_to_search, $index_to_start_search_from);

有没有可以实现上述伪代码的函数 这样$key 将返回 index: 8

我的意思是我想从索引 6 开始搜索,以便它返回值为 5 的索引 8=>,因为值 5 是我在数组中搜索的目标。

【问题讨论】:

  • 您能否为示例数组提供您想要开始的键,因为它可以节省试图回答您问题的人的时间。不过,也许this 可能会有所帮助。
  • 提供的值

标签: php arrays search indexing


【解决方案1】:

我认为你可以使用array_slice

$needle_to_search = 5;
$array_to_search = [6,8,4,9,7,5,9,4,5,9,3,5,4,6,7];
$index_to_start_search_from = 6;

// 输出

Array
(
    [0] => 6
    [1] => 8
    [2] => 4
    [3] => 9
    [4] => 7
    [5] => 5
    [6] => 9
    [7] => 4
    [8] => 5
    [9] => 9
    [10] => 3
    [11] => 5
    [12] => 4
    [13] => 6
    [14] => 7
)

// return 5
echo array_search($needle_to_search, $array_to_search);

// return 8
echo array_search($needle_to_search, array_slice($array_to_search, $index_to_start_search_from, null, true));

【讨论】:

  • 谢谢但不满意
  • 为什么是@myckhel,那么您的期望如何。你能澄清一下吗
  • 希望你现在明白了
  • 非常感谢,这正是我需要的
猜你喜欢
  • 2011-01-15
  • 1970-01-01
  • 1970-01-01
  • 2019-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-12
相关资源
最近更新 更多