在对象中包含新项(PHP)

时间:2011-06-06 15:46:06

标签: php oop

如下所示,每个Object行都有pricename个属性。我想在每一行中再添加一个属性category。所以,这里有一个棘手的问题:我怎么能这样做?

stdClass Object
(
    [0] => stdClass Object
        (
            [price] => 12.99
            [name] => Million Dollar Baby (Two-Disc Widescreen)
        )

    [1] => stdClass Object
        (
            [price] => 599.95
            [name] => Screets Kiddiebank Experience
        )

    [2] => stdClass Object
        (
            [price] => 1999.00
            [name] => Screets Kiddiebank Unlimited
        )

)

2 个答案:

答案 0 :(得分:3)

这是你在找什么?

<?php
$p1 = new stdClass();
$p1->price = 12.99;
$p1->name = "Million Dollar Baby (Two-Disc Widescreen)";

$p2 = new stdClass();
$p2->price = 599.95;
$p2->name = "Screets Kiddiebank Experience";

$p3 = new stdClass();
$p3->price = 1999.00;
$p3->name = "Screets Kiddiebank Unlimited";

$products = array($p1, $p2, $p3);
foreach($products as $product) {
    $product->category = "Some category";
}

var_dump($products);
?>

答案 1 :(得分:2)

你的意思是这样吗?

$objects->{0}->category = 'foo';
$objects->{1}->category = 'bar';
$objects->{2}->category = 'foo';