PHP中的多维数组

3

如何将项目添加到多维数组中?基本上,我正在制作一个应用程序,计算人们在超市购买的物品和数量。

Sue购买了2罐黄油和1支牙膏

John购买了1个桃子和1根香蕉。

我认为这个数组看起来像这样:

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

我的当前代码只能记录商品和商品数量。

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;
    }
}

我不知道如何将这个放进每个人的数组中。
谢谢!

看起来你已经在使用购物车类了,所以Zack的答案应该很适合。我建议将$items设为私有(或受保护),并添加一个访问器函数。 - James Socol
Ben,请注意,这是一个完全可以询问初学者问题的地方。告诉你反面意见的人是没有正确信息的。 - Rex M
谢谢Rex!也感谢其他回答我的问题的人 :) - Ben McRae
4个回答

4

你可以将代码封装进一个类中,这可能会更容易操作。例如,每个人都可以成为一个类,然后赋予他们属性。

一旦你涉及到多维数组,代码的维护变得更加困难。

例如(这是伪代码):

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;
}

嗨,Zack,我需要将它保存在数组中,因为我要在我的页面之间保存它在会话中!但还是谢谢! - Ben McRae
1
只是提供信息,您可以将类/对象保存在会话数据中。将数据保存为序列化变量。请参见http://us.php.net/serialize - Rob
嗨,罗布!我之前在使用序列化来处理我的原始数组!我不知道这可以用于除了数组以外的其他情况,感谢你提醒我! - Ben McRae
1
只要类定义已加载或可以自动加载,PHP就会为您序列化/反序列化。 - James Socol

3
嗯,也许我没有看到这里的多维性?
$sue = array();
$sue['butter'] = 2;
$sue['toothpaste'] = 1;

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

我认为你展示的函数可以与上述内容一起使用。

嗨Tomalak,我认为你的多维数组正是我想要编写的。只是我不确定如何使用上述方法来设置它! - Ben McRae
2
@Ben McRae:我认为你有一个误解。 :) 我的数组根本不是多维的。它只有一个键和值的维度。而你现在使用的函数实际上可以与它一起使用。 - Tomalak

1

你不需要像这里一样创建另一个数组来保存项目的数量:

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

我觉得这样做可能会有效:

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

这样你就可以创建一个客户名称的数组。然后在每个客户数组中,你都有一个他们产品的数组。然后每个产品都保存了客户购买的该产品数量。


0
$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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接