2010-08-06 51 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