2

我想知道什么时候,是否适合使用 anArrayObject()而不是 an Array()?这是我一直在研究的一个例子。

对我来说,我认为一个简单的数组会起作用,但我ArrayObject()在手册中找到了,我想知道,如果使用一个而不是一个简单的数组会更好。

public function calculateTotal(){
    if(count($this->items) > 0){
        $n = 0;
        foreach($this->items as $item){
            if($item->size == 'small'){
                $k = $item->price->small;
            }
            if($item->size == 'large'){
                $k = $item->price->large;
            }
            $n += $k * $item->quantity;
        }
    }else{
        $n = 0;
    }
    return (int) $n;
}

现在我很困惑我应该如何构造这个对象。

例如,我可以用短数组语法构造它吗?

$this->items = []; //empty object

还是我应该构造为 Array 对象

$this->items = new ArrayObject(); //empty object

我也对我应该如何将新项目推送到数组感到困惑。

我正在编写以下函数:

另外我应该如何将数组对象附加到这个对象?

这个好吗?

public function additem($item){
        $add = [
        'item_id'=>$this->item_id(),
        'name'=>$item['name'],
        'size',$item['size'],
        'quantity'=>$item['quantity'],
        'price'=>[
            'large'=>$item['price'],
            'small'=>$item['price']
            ]
        ]
        array_push($this->items,$add);
}

还是我应该改用ArrayObject::append()其他方法?

我查了手册,上面写着:

public void ArrayObject::append ( mixed $value )
Appends a new value as the last element.

Note:
This method cannot be called when the ArrayObject was constructed from an object. Use ArrayObject::offsetSet() instead.

来源http://php.net/manual/en/arrayobject.append.php

我现在问这个的原因是,稍后当需要从这个列表中删除项目时,我将如何找到我正在寻找的东西?我可以in_array()在这个对象上使用吗?

对于这些对您来说可能看起来很愚蠢的问题,我提前道歉,但请记住,我仍在学习一些更具技术性的东西。谢谢

4

1 回答 1

2

您的第一个片段中没有任何内容需要ArrayObject. KISS 并使用简单的数组:array_push($this->items,$add);或者$this->items []= $add;都可以。

calculateTotal附带说明一下,您的代码之间存在差异add:您必须决定您的item结构是数组 ( $item['price']) 还是对象 ( $item->price)。我的建议是使用数组,但这完全取决于你。

于 2014-08-19T08:26:51.293 回答