我们如何使用内置的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
任务看起来应该是封装的。
答案 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
[]
);