使用内置的PHP数组函数完成此foreach任务

时间:2018-01-06 12:16:59

标签: php arrays refactoring

我们如何使用内置的PHP数组函数完成这个foreach任务?

$requestProducts = $this->request['products'];

$products = [];

foreach ($requestProducts as $product) {
    if (!empty($product['search']['value'])) {
        array_push($products, [
            'name' => $product['name'],
            'title' => $product['title'],
            'search' => $product['search']['value']
        ]);
    }
}

我想以这种方式拥有但没有空值。

$requestProducts = $this->request['products'];

$products = array_map(function ($product) {
    if (!empty($product['search']['value'])) {
        return [
            'name' => $product['name'],
            'title' => $product['title'],
            'search' => $product['search']['value']
        ];
    }
    return null; // without null
}, $requestProducts);

$products = array_filter($products) // without this

任务看起来应该是封装的。

1 个答案:

答案 0 :(得分:1)

array_reduce的解决方案:

$requestProducts = $this->request['products'];

$products = array_reduce(
    // your values
    $requestProducts,                   
    // reducing function
    function ($t, $product) {
        if (!empty($product['search']['value'])) {
            $t[] = [
                'name' => $product['name'],
                'title' => $product['title'],
                'search' => $product['search']['value']
            ];
        }

        return $t;
    }, 
    // initial value for reduced items
    []
);