2012-11-21 74 views
0

將對象數組映射到對象的鍵值數組的最簡單方法是什麼,其中鍵是對象的某些屬性?將數組轉換爲不帶迭代的鍵值數組

例如:

class Cartoon 
{ 
    public $title; 
    public function __construct($title) 
    { 
    $this->title = $title; 
    } 
} 

$cartoons = array(new Cartoon('Tom and Jerry'), new Cartoon('Cheburashka')); 

$mappedCartoons = array(); 

foreach ($cartoons as $cartoon) 
{ 
    $mappedCartoons[$cartoon->title] = $cartoon; 
} 

print_r ($mappedCartoons); 

PS。我想知道是否迭代和額外變量$mappedCartoons可以處置?

回答

4

您可以使用array_reduce來實現您的目標。

<?php 

$cartoons = array_reduce($cartoons, function($result, $cartoon) { 
    $result[$cartoon->title] = $cartoon; 
    return $result; 
}, array()); 

?> 

的想法是不是我的,在這裏找到:http://www.danielauener.com/howto-use-array_map-functionality-on-an-associative-array-changing-keys-and-values/

+0

這太棒了!現在array_reduce是我在array_map之後的第二個最喜歡的朋友。 – Dziamid

+0

在幕後,仍然涉及迭代過程。但不錯的建議。 +1也許我在這方面誤解了OP,首先。 –

0

如果必須使用基本陣列創建它們時,你可以簡單地鍵入出的鍵:

$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"; 
} 
+0

謝謝,但我不打算使用通用類對象的集合,唯一的本地陣列。 – Dziamid

0

我想不出一種不涉及迭代的方式。我可以認爲不需要額外的變量,雖然的方法:

$cartoons = array(new Cartoon('Tom and Jerry'), new Cartoon('Cheburashka')); 
foreach($cartoons as $key => $cartoon) 
{ 
    $cartoons[ $cartoon->title ] = $cartoon; 
    unset($cartoons[ $key ]); 
} 

var_dump($cartoons); 

然而,the documentation of foreach筆記:

作爲的foreach依賴內部數組指針的循環可能會導致內改變它意外的行爲。

我不完全確定這也適用於我的示例。也許別人可以在這裏發出邀請。

爲了安全起見,或許這種替代是比較合適的,因爲它發起$len$cartoons初始長度,迭代之前:

$cartoons = array(new Cartoon('Tom and Jerry'), new Cartoon('Cheburashka')); 
for($i = 0, $len = count($cartoons); $i < $len; $i++) 
{ 
    $cartoon = $cartoons[ $i ]; 
    $cartoons[ $cartoon->title ] = $cartoon; 
    unset($cartoons[ $i ]); 
} 

var_dump($cartoons); 

這個例子假設初始$cartoons具有「適當的」順序編號按鍵,不過,從0開始。