php - 如何访问类对象以在 PHP 中显示总价?
问题描述
问题:analytics2.php 还通过调用 getCustomerList() 从 CustomerDAO 获得一个客户对象的索引数组。处理客户对象的索引数组以识别花费最多的客户。对于“bob”(如上图的内存状态图所示),他以每个 5 美元(小计:25 美元)的价格购买了 5 个苹果,以每个 10 美元(小计:20 美元)的价格购买了 2 个香蕉。他总共花了45美元。
以下是我尝试编写的analytics2.php,但我不知道如何进一步获取每个客户的总价:
require_once 'CustomerDAO.php';
$dao = new CustomerDAO();
$customer_list = $dao->getCustomerList();
// YOUR CODE GOES HERE
$subtotal = 0;
$total = 0;
$mostSpent = 0;
$customerList = [];
foreach($customer_list as $customerObj){
$customerName = $customerObj->getName();
$order_list = $customerObj->getOrderList();
// var_dump($order_list);
foreach($order_list as $orderObj){
$qty = $orderObj->getQuantity();
$price = $orderObj->getItem()->getPrice();
if(sizeof($order_list) > 1){
for($i = 0; $i < sizeof($order_list); $i++){
$subtotalList = [];
$subtotal = $qty * $price;
$subtotalList[] = $subtotal;
}
}
else{
$subtotal = $qty * $price;
}
// var_dump($qty);
}
}
echo "The customer who spent the most money is ... (... dollars)";
###
这是 CustomerDAO.php:
<?php
// DO NOT MODIFY THE CODE BELOW
class CustomerDAO{
private $customerList;
# Constructor
# Simulates retrieval from a database
public function __construct(){
# Items
$apple = new Item("apple",5);
$banana = new Item("banana",10);
$orange = new Item("orange",15);
# Orders
$order1 = new Order($apple,5);
$order2 = new Order($banana,2);
$order3 = new Order($apple,10);
$order4 = new Order($apple,1000);
$orderList1 = [$order2, $order1];
$orderList2 = [$order4];
$orderList3 = [$order1, $order2, $order3];
# Customers
$bob = new Customer("bob", $orderList1);
$jane = new Customer("jane", $orderList2);
$jill = new Customer("jill", $orderList3);
$this->customerList = [$bob, $jane, $jill];
}
# Get a list of customers
# Input: Nothing
# Output: A list of Customer objects
public function getCustomerList(){
return $this->customerList;
}
} ?>
解决方案
推荐阅读
- swift - NSCollectionViewItem 和对可访问性的支持
- javascript - v-on 处理程序中的错误:“TypeError:无法将未定义或 null 转换为对象”
- python - 列表中元素的总和
- opencv - 可以应用opencv图像变换将曲线变为直线吗?
- php - 搜索、过滤数据库表格更安全
- javascript - Dom-to-image js库问题
- c# - Firestore - 权限缺失或不足
- flutter - 在 Flutter 上创建加载页面
- android - 如何使用颤振从 Firestore 中的特定文档中检索字段值?
- hp-uft - 无法在 UFT 中使用 Object spy 找到 webElements