2013-03-27 44 views
0

獲取單個值下面我有數組結果從一個數組

Array ([0] => Item Object ([name:protected] => My Super Cool Toy [price:protected] =>  10.99)) 

我需要從這個數組得到[name:protected] => My Super Cool Toy

請告訴我如何得到它,

我將粘貼下面

class ShoppingCart 
{ 
private $items = array(); 
private $n_items = 0; 
function addItem(Item $item) 
{ 
$this->items[] = $item; 
$this->n_items = $this->n_items + 1; 
print_r($this->items); 

} 
} 

我的課
class Item { 
protected $name; 
protected $price; 

public function __construct($name, $price) { 
    $this->name = $name; 
    $this->price = $price; 
} 

public function getName() { 
    echo "item is $this->name"; 
    return $this->name; 
} 

public function getPrice() { 
    return $this->price; 
} 

} 

require_once('AddingMachine.php'); 
require_once('item.php'); 
//$arrayofnumbers = array(100,200); 

$objectname = new ShoppingCart(); 
$objectname->addItem(new Item('My Super Cool Toy', 10.99)); 

$obname = new Item($items,44); 
$obname->getName(); 

感謝

回答

0

如果我沒有得到它,你得到這個數組中的購物類,在方法的addItem,所以要訪問它,你只需要使用相應的getter方法,如:

$this->items[0]->getName(); 
0

你可以試試:

$objectname = new ShoppingCart(); 
$objectname->addItem(new Item('My Super Cool Toy', 10.99)); 

foreach ($objectname->getItems() as $item) { 
    echo $item->getName(), PHP_EOL; 
} 

修改後的分類

class ShoppingCart { 
    private $items = array(); 
    private $n_items = 0; 

    function addItem(Item $item) { 
     $this->items[] = $item; 
     $this->n_items = $this->n_items + 1; 
    } 

    function getItems($n = null) { 
     return $n === null ? $this->items : (isset($this->items[$n]) ? : $this->items[$n]); 
    } 
}