更新阵列

时间:2010-08-06 15:07:49

标签: php arrays

$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 )
)

怎么做?

感谢。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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);

?>

顺便说一下,您可能希望将变量命名约定更新为更有意义的内容。 : - )