php - 使用数组过滤器重写
问题描述
我将如何在foreach
某些条件下使用编写以下内容array_filter
?
foreach ($categories as $category) {
if ($this->request->getParam('category_id')) {
if ($category->getCategoryId() == $this->request->getParam('category_id')) {
$selectedCategory = $category;
break;
}
} else {
No category id in request. Select the first one.
if (array_key_exists(0, $categoryTree) &&
$category->getCategoryId() == $categoryTree[0]['id']
) {
$selectedCategory = $category;
break;
}
}
}
解决方案
I think you want an intersection function and not an array filter.
function key_compare_func($key1, $key2)
{
if ($key1 == $key2->getCategoryId()) {
return 1;
} else {
return 0;
}
}
$selectedCategory = array_intersect_ukey(
$this>request>getParam('category_id'),
$categories,
'key_compare_func'
)
For more information on the different array functions you can look at the PHP manual
推荐阅读
- python - 带有open cv python响应的索引错误数组
- grafana - 在 grafana 中显示带有查询字符串参数的完整 URL
- javascript - 解决 Js 对象属性查找
- python - 检查字典值(列表)是否已经存在并更新
- ios - 使用 TestFlight beta 覆盖 React Native 调试应用
- c++ - wxString(const std::string&) 在调试构建中引发读取访问冲突
- ethers.js - factory.deploy() 和 contract.deployed() 的返回值之间返回的对象之间的区别?
- r - VAR模型的蒙特卡罗模拟
- javascript - 为什么我的 stringify 不能在“if”语句中解析?
- windows - Docker-Compose 在 Windows Server 2022 上不起作用