繁体   English   中英

在PHP中查找数组中元素的索引

[英]Find index of an element in an array in PHP

我试图在一个数组中找到一个字符串,然后返回索引并检查另一个数组中的索引以查看它是否匹配(我分别在数组中寻找打开时间和匹配关闭时间)。

该字符串可能在$openList出现$openList ,并且不应该停止检查,直到在$openList$closeList中都找到一对匹配的时间$closeList array_search只找到第一个匹配项,因此在创建一个有效且有效的循环时遇到了麻烦(我将使用不同的搜索值多次运行此循环)。

到目前为止,我有这样的事情:

$openList = array("10:00", "9:00", "10:15", "9:00", "2:30");
$closeList = array("2:15", "5:30", "10:30", "10:00", "3:00");

$found_key = false;
while (($key = array_search("9:00", $openList)) !== NULL) {
  if ($closeList[$key] == "10:00") {
    $found_key = true;
    echo "found it at position ".$key;
    break;
  }
}
if (!$found_key) echo "time doesn't exist";

如何有效地解决问题?

可以肯定,array_keys正是您要寻找的东西:

http://www.php.net/manual/zh/function.array-keys.php

如果列表中没有"9:00" ,则当前循环将永远运行。 而是使用foreach循环浏览$openList数组:

foreach ( $openList as $startTimeKey => $startTimeValue )
{
    //Found our start time
    if ( $startTimeKey === "9:00" && isset( $closeList[ $startTimeValue ] ) && $closeList[ $startTimeValue ] === "10:00" )
    {
        $found_key = true;
        break;
    }
}

感谢您提供有关array_keys @David Nguyen的提示。 这似乎可行:

$openList = array("10:00", "9:00", "10:15", "9:00", "2:30");
$closeList = array("2:15", "5:30", "10:30", "10:00", "3:00");

$found_key = false;
foreach (array_keys($openList, "9:00") AS $key) {
  if ($closeList[$key] == "10:00") {
    $found_key = true;
    echo "found it at position ".$key;
    break;
  }
}
if (!$found_key) echo "time doesn't exist";

暂无
暂无

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

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