PHP中的多维数组

How do i add items into a multidimensional array? Basically i am making an application which calculates what people are buying in a suppermarket and how much of it.

Sue buys 2 tubs of butter and 1. toothpaste

John buys 1 peach and 1 banana.

I think the array would look something like this

$sue[butter] = array(); 
$sue[butter][] = 2;
$sue[toothpaste] = array(); 
$sue[toothpaste][] = 1;
$john[peach] = array(); 
$john[peach][] = 1;
$john[banana] = array(); 
$john[banana][] = 1;

My current code can only record the item and the item quantity.

public $items = array();

public function AddItem($product_id)
{
    if (array_key_exists($product_id , $this->items))
    {
        $this->items[$product_id] = $this ->items[$product_id] + 1;
    } else {
        $this->items[$product_id] = 1;
    }
}

I just dont know how to put this inside an array for each person.

Thanks!

Instead of doing this, you might find it easier to encapsulate into a class. For instance, have each person be a class, and then give them attributes.

Once you get into multidimensional arrays, it becomes more difficult to maintain your code.

For instance (this is pseudocode):

class Customer {
    //this is an array of FoodItem objects.
    private $foodItems[];

    // any other methods needed for access here
}

class FoodItem {
    //could be a String, or whatever it needs to be
    private $itemType;

    //the number of that item purchased
    private $numPurchased;
}

Hm, maybe I fail to see the multi-dimensionality here?

$sue = array();
$sue['butter'] = 2;
$sue['toothpaste'] = 1;

$john = array();
$john['peach'] = 1;
$john['banana'] = 1;

I think the function you've shown would work with the above.

$data = array();
$data["persons"] = array("Sue","John");
$data["articles"] = array("butter","toothpaste","peach","banana");

$data["carts"] = array();

$data["carts"][0][0] = 2; // sue's 2 butter packets
$data["carts"][0][1] = 1; // sue's 1 tooth paste

$data["carts"][1][2] = 1; // john's peach
$data["carts"][1][3] = 1; // john's banana

You dont need to create another array to hold the number of items like you did here:

$sue[butter] = array(); 
$sue[butter][] = 2;

I think something like this would work:

$customers[sue][butter] = 2; 
$customers[sue][toothpaste] = 1; 
$customers[john][peach] = 1; 
$customers[john][banana] = 1;

This way you create an array of customer names. Then in each customer array you have an array of their products. Then each product holds the number of that product the customer bought.