我试图在数组中查找一个字符串,然后返回索引并在另一个数组中检查该索引以查看它是否匹配(我分别在数组中寻找打开时间和匹配关闭时间)。
该字符串可能会在$openList
中出现不止一次,并且它不应该停止检查,直到在$openList
和$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/en/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";