Review this generated product-feed function before it serves production data.
Apply defaults while letting each product override them, keep zero-stock products, sort by normalized name, and return public JSON without internal cost.
php
<?php
function buildProductFeed(array $products, array $defaults): string
{
$visible = array_filter(
$products,
fn(array $product): bool => $product['stock'],
);
$rows = array_map(
function (array $product) use ($defaults): array {
$row = array_merge($product, $defaults);
return [
'sku' => $row['sku'],
'name' => $row['name'],
'stock' => $row['stock'],
'cost' => $row['cost'],
];
},
$visible,
);
usort(
$rows,
fn(array $a, array $b): int => strtolower($a['name']) <=> strtolower($b['name']),
);
return json_encode($rows, JSON_THROW_ON_ERROR);
}
generated code is illustrative, not from any one model