<?php
/**
* 購入された商品の一覧を取得する(本来はDBなどから取得する想定)
*
* @return array<int, array{name: string, price: int, quantity: int, userId: int}>
*/
function getBoughtItemsAll()
{
return [
['userId' => 1, 'name' => 'Apple', 'price' => 240, 'quantity' => 3],
['userId' => 1, 'name' => 'Banana', 'price' => 210, 'quantity' => 6],
];
}
/**
* 指定されたユーザーIDに紐づく購入商品の一覧を取得する
*
* @return array<int, array{name: string, price: int, quantity: int, userId: int}>
*/
function getBoughtItemsByUserId($userId)
{
$allItems = getBoughtItemsAll();
$userItems = [];
foreach ($allItems as $item) {
if ($item['userId'] === $userId) {
$userItems[] = $item;
}
}
return $userItems;
}
/**
* 購入商品の合計金額と平均金額を計算する
*
* @param array<int, array{name: string, price: int, quantity: int, userId: int}> $boughtItems
* @return array{total: int, average: float}
*/
function summary($boughtItems)
{
$total = 0;
foreach ($boughtItems as $item) {
$total += $item['price'] * $item['quantity'];
}
$average = $total / count($boughtItems);
return [
'total' => $total,
'average' => $average,
];
}
function main()
{
$currentUserId = 2;
$boughtItems = getBoughtItemsByUserId($currentUserId);
$data = summary($boughtItems);
var_export($data);
}
main();