2010-08-06 65 views
11

$var是一個數組:更新數組

Array (
[0] => stdClass Object ([ID] => 113 [title] => text) 
[1] => stdClass Object ([ID] => 114 [title] => text text text) 
[2] => stdClass Object ([ID] => 115 [title] => text text) 
[3] => stdClass Object ([ID] => 116 [title] => text) 
) 

要分兩步更新:

  • 獲取每個對象的[ID]並拋出其值設置爲位置計數器(我的意思是[0], [1], [2], [3]
  • 刪除[ID]投擲後

最後更新陣列($new_var)應該是這樣的:

Array (
[113] => stdClass Object ([title] => text) 
[114] => stdClass Object ([title] => text text text) 
[115] => stdClass Object ([title] => text text) 
[116] => stdClass Object ([title] => text) 
) 

如何做到這一點?

謝謝。

回答

19
$new_array = array(); 
foreach ($var as $object) 
{ 
    $temp_object = clone $object; 
    unset($temp_object->id); 
    $new_array[$object->id] = $temp_object; 
} 

我假設有更多的對象,你只是想刪除ID。如果您只想要標題,則無需克隆該對象,只需設置$new_array[$object->id] = $object->title即可。

+0

+1比我的整潔的解決方案。 :-) – 2010-08-06 15:14:27

2

我還以爲這會工作(沒有解釋訪問,所以它可能需要的調整):

<?php 

    class TestObject { 
     public $id; 
     public $title; 

     public function __construct($id, $title) { 

      $this->id = $id; 
      $this->title = $title; 

      return true; 
     } 
    } 

    $var = array(new TestObject(11, 'Text 1'), 
       new TestObject(12, 'Text 2'), 
       new TestObject(13, 'Text 3')); 
    $new_var = array(); 

    foreach($var as $element) { 
     $new_var[$element->id] = array('title' => $element->title); 
    } 

    print_r($new_var); 

?> 

順便說一句,你可能要更新你的變量命名約定更有意義。 :-)

+0

不起作用,出現錯誤:不能使用stdClass類型的對象作爲數組 – James 2010-08-06 15:22:18

+0

@Ignatz - 現在可以訪問帶有PHP的計算機 - 我修復了代碼並提供了一個更完整的示例。順便說一句,如果你有一個getter/setter,你應該把類變量改爲private,並在foreach迭代器中使用setter。 – 2010-08-06 16:06:15

+0

感謝您的時間 – James 2010-08-06 19:03:19