我正在尝试使用array_search
来查找数组中值的键,我有以下简单的代码:
$current_user_existing_shopping_bag_string = '1446784/-/3/-/£797.00(_)902982/-/4/-/£148.80(_) ';
$current_user_existing_shopping_bag_array = explode('(_)', $current_user_existing_shopping_bag_string);
$key = array_search($current_user_existing_shopping_bag_array, '902982');
echo $key;
但是我不知道为什么这不返回数组中值的键,但它应该返回。我已经尝试了几个小时的各种解决方案,但仍然没有运气。
有人能够给我一个指针,为什么这不返回数组中值的键?
谢谢
这是因为array_search
使用运算符比较字符串===
而不是正则表达式或任何类型的strpos
。
你搜索902982
但字符串是902982/-/4/-/£148.80
的,因此它们在任何方面都不相等。
对于您想要实现的目标,您可以使用preg_grep:
$result = preg_grep('/' . preg_quote($search) . '/', $current_user_existing_shopping_bag_array);
然后,您可以从生成的数组中获取所需的密钥。