<?php
// bad code
function example () {
$result = [];
$products = [];
$disabledProductIds = [];
// 透過 by reference 更新變數資料
$this->getProducts($products);
foreach($products as $key => $product) {
// 移除狀態為 false 的商品
if ($product->status === false) {
unset($products[$key]);
$disabledProductIds[] = $product->id;
continue;
}
// 商品名字加上原本索引
$product->name .= "($key)";
}
$products = array_value($products);
$result['products'] = $products;
$result['disabled_ids'] = $disabledProductIds;
return $result;
}
<?php
// good code
// 總共只使用一個變數
function example () {
// `get products` 應直接回傳 products,而些 reference
$products = $this->getProducts();
// 雖然會多跑一次迴圈,但對於可讀性來說,是非常划算
return [
'products' => collect($products)
// 已啟用商品
->filter(fn($product) => $product->status)
->map(fn($prodcut, $key) => [
'id' => $product->id,
'name' => "{$product->name}({$key})",
'status' => $product->status,
])
->values()
->toArray(),
'disabled_ids' => collect($products)
// 已停用商品
->filter(fn($product) => $product->status === false)
->pluck('id')
->toArray(),
];
}
// 單層 array
return [
// 商品
'id' => $product->id,
'name' => $product->name,
'created_at' => $product->created_at->toDateTimeString(),
'updated_at' => $product->updated_at->toDateTimeString(),
// 商品規格
'specs' => $product->specs->map(fn($spec) => [
'id' => $spec->id,
'name' => $spec->name,
'stocks' => $spec->stocks,
])
];
// 多層 Array 或多層 Collection
return collect($products)->map(fn($product) => [
// 商品
'id' => $product->id,
'name' => $product->name,
'created_at' => $product->created_at->toDateTimeString(),
'updated_at' => $product->updated_at->toDateTimeString(),
// 商品規格
'specs' => $product->specs->map(fn($spec) => [
'id' => $spec->id,
'name' => $spec->name,
'stocks' => $spec->stocks,
])
]);