如果必須使用基本陣列創建它們時,你可以簡單地鍵入出的鍵:
$cartoons = array(
'Tom and Jerry' => new Cartoon('Tom and Jerry'),
'Cheburashka' => new Cartoon('Cheburashka'),
);
或者,可以創建用於實現不同的陣列/迭代相關接口,並且可以被用作規則陣列容器對象:
class CartoonArray extends ArrayObject {
public function __construct($input, $flags = 0, $iterator_class = "ArrayIterator") {
parent::__construct(array(), $flags, $iterator_class);
// since the original ArrayObject implemented in C and they don't it won't pick up our overriden ossetSet we have to type it out here explicitly
foreach ($input as $value) {
$this->offsetSet(null, $value);
}
}
public function offsetSet($index, $value) {
parent::offsetSet($value->title, $value);
}
}
$cartoons = new CartoonArray(array(new Cartoon('Tom and Jerry'), new Cartoon('Cheburashka')));
$cartoons[] = new Cartoon('Sesame street');
print $cartoons['Tom and Jerry']->title;
unset($cartoons['Tom and Jerry']);
foreach ($cartoons as $k => $v) {
print $k."\n";
}
這太棒了!現在array_reduce是我在array_map之後的第二個最喜歡的朋友。 – Dziamid
在幕後,仍然涉及迭代過程。但不錯的建議。 +1也許我在這方面誤解了OP,首先。 –