在 PHP 中使用 in_array 从数组中搜索时查找索引
我的目标是找出运算符是什么,以及它在原始 $operatorArray 中的位置(其中包含各种运算符,例如“+”、“-”等...)
所以我设法检查 $operator 何时匹配与我现有的 $operatorArray 中的另一个运算符,但是我需要知道在 $operatorArray 中的何处找到它。
foreach ($_SESSION['explodedQ'] as $operator){ //search through the user input for the operator.
if (in_array("$operator", $operatorArray)) { //if the operator that we found is in the array, then tell us what it is
print_r("$operator"); //prints the operator found
print_r("$positionNumber"); //prints where the operator is
} //if operator
else{
$positionNumber++; //The variable which keeps count on where the array is searching.
}
我尝试过 Google/Stack 搜索,但问题是,我实际上不知道要 Google 搜索什么。我搜索过诸如“从 in_array 中查找索引”等内容......但我不知道该怎么做。如果您能为我提供一种简单的方法来了解如何实现这一目标,我将不胜感激。感谢您抽出时间。
My aim is to find out what the operator is, and where it was in the original $operatorArray (which contains the various operators such as "+", "-" etc... )
So I have managed to check when $operator matches with another operator in my existing $operatorArray, however I need to know where in $operatorArray it is found.
foreach ($_SESSION['explodedQ'] as $operator){ //search through the user input for the operator.
if (in_array("$operator", $operatorArray)) { //if the operator that we found is in the array, then tell us what it is
print_r("$operator"); //prints the operator found
print_r("$positionNumber"); //prints where the operator is
} //if operator
else{
$positionNumber++; //The variable which keeps count on where the array is searching.
}
I've tried Google/Stack searching, but the thing is, I don't actually know what to Google search. I've searched for things like "find index from in_array" etc... and I can't see how to do it. If you could provide me with a simple way to understand how to achieve this, I would be greatful. Thanks for your time.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
array_search 将执行您要查找的操作
array_search will do what you are looking for
直接取自 PHP 手册:
array_search()
- 在数组中搜索给定值,如果成功则返回相应的键。如果您正在搜索非关联数组,它将返回相应的键,即您要查找的索引。对于非连续索引数组(即
array(1 => 'Foo', 3 => 'Bar', ...)
),您可以使用array_values() 的结果
并在其中搜索。Taken straight from the PHP manual:
array_search()
- Searches the array for a given value and returns the corresponding key if successfulIf you're searching a non-associative array, it returns the corresponding key, which is the index you're looking for. For non-consecutively indexed arrays (i.e.
array(1 => 'Foo', 3 => 'Bar', ...)
) you can use the result ofarray_values()
and search in it.您可能想尝试一下
这样,一旦
in_array()
命中正确的$operator
,您就可以打印$index
。You might want to give this a try
That way you can print the
$index
as soon as yourin_array()
hits the right$operator
.我认为你需要 array_search()
i think you need array_search()
使用:
Use: