首页 > 解决方案 > 如何访问类对象以在 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;
    }
}   ?>

预期的输出应该是这样的: 在此处输入图像描述

标签: php

解决方案


推荐阅读