首页 > 解决方案 > 使用数组过滤器重写

问题描述

我将如何在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;
            }
        }
    }

标签: phparray-filter

解决方案


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


推荐阅读