Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/238.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 使用数组过滤器重写_Php_Array Filter - Fatal编程技术网

Php 使用数组过滤器重写

Php 使用数组过滤器重写,php,array-filter,Php,Array Filter,如何使用array\u filter在某些条件下编写以下foreach foreach($categories作为$category){ if($this->request->getParam('category_id')){ 如果($category->getCategoryId()==$this->request->getParam('category_id')){ $selectedCategory=$category; 打破 } }否则{ 请求中没有类别id。请选择第一个类别id。 如果

如何使用
array\u filter
在某些条件下编写以下
foreach

foreach($categories作为$category){
if($this->request->getParam('category_id')){
如果($category->getCategoryId()==$this->request->getParam('category_id')){
$selectedCategory=$category;
打破
}
}否则{
请求中没有类别id。请选择第一个类别id。
如果(数组\键\存在(0,$categoryTree)&&
$category->getCategoryId()==$categoryTree[0]['id']
) {
$selectedCategory=$category;
打破
}
}
}

首先,在这种情况下使用
数组\u过滤器是没有帮助的,因为它减少了数组而不是选择元素。但是为了展示它的原理,你可以把代码重写成这样

if($this->request->getParam('category_id')){
  $filteredCategories = array_filter($categories, function ($category) use ($this){
    return $category->getCategoryId() == $this->request->getParam('category_id');
  });
  if(count($filteredCategories)>0){
    return $filteredCategories[0];
  }
} else {
  [...]
}

我想你需要的是交集函数,而不是数组过滤器

    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'
    )

有关不同数组函数的更多信息,请参见

我有一个更好的问题-为什么要这样做?此代码似乎不适合进行该修改。此代码也是无效的,并且您没有显示某些变量的来源。
array\u filter
会将数组缩减为自身的子集。因此,它可能会生成一个包含一个元素的数组,一打或根本没有。这里您从数组中选择一个元素,
array\u filter
在这种情况下没有帮助。