php - 比较两个数字,如果它遵循数组中的序列
问题描述
我不太确定该怎么做,但情况就是这样。
我有一个遵循特定顺序的字符串数组。
$array = ['A','B','C','D','E'];
我有两个带字符串的输入,我想做的是根据给定的数组检查两个输入字符串是否按顺序排列。
例如
$array = ['A','B','C','D','E'];
$input1 = 'B';
$input2 = 'D';
//this should return true
但是,如果是这种情况
$array = ['A','B','C','D','E'];
$input1 = 'D';
$input2 = 'A';
//this should return false
$input1
应该总是先于$input2
我已经尝试了几种使用循环的方法来做到这一点,但我无法得到想要的结果。
感谢任何帮助。谢谢!
解决方案
你可以找到两个输入的索引array_search()
为了使两个输入按顺序排列,第一个输入的索引必须低于第二个输入的索引。如果没有找到也array_search()
返回。false
function inSequence($array, $input1, $input2) {
$index1 = array_search($input1, $array);
$index2 = array_search($input2, $array);
if($index1 === false || $index2 === false) return false;
return $index1 < $index2;
}
推荐阅读
- css - vis-timeline - 将自定义时间标记标签放置在时间轴上方
- javascript - 如果我不想对原始请求做任何事情,我应该在 JS Service Worker onFetch 回调函数中返回一个承诺吗?
- php - Mailtrap 不适用于 Wordpress localhost(在 Xampp 上运行)
- php - CURL API 用 php 和 html 在表格中显示数据
- c++ - Docker 镜像问题查找头文件
- java - 在解决类路径问题时,getproperty() 和 getPackage().getImplementationVersion() 返回 null
- php - 如何在父类方法中克隆子类实例
- android - ConstraintLayout 中的 Start 和 Left 有什么区别?
- python - 如何在两列上的两个数据框之间创建合并,而不在左侧引入额外的行?
- visual-studio-code - 键绑定:焦点编辑器的索引是否有“when”子句,或者它是否是最后一个?