【问题标题】:When is it appropriate to use an ArrayObject instead of an Array什么时候适合使用 ArrayObject 而不是 Array
【发布时间】:2014-08-19 05:40:14
【问题描述】:

我想知道何时使用ArrayObject() 代替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

或者我应该构造一个数组对象

$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() 吗?

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

【问题讨论】:

    标签: php arrays arrayobject


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢乔治。当我读到你的帖子时,我已经使用了简单的数组。有时我只是厌倦了输入方括号
    猜你喜欢
    • 1970-01-01
    • 2011-09-13
    • 1970-01-01
    • 2019-02-28
    • 2019-08-25
    • 2010-12-20
    • 2010-10-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多