php 更新数组

yhuiod9q  于 2022-12-10  发布在  PHP
关注(0)|答案(2)|浏览(121)

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

这怎么办?

  • 谢谢-谢谢
yhqotfr8

yhqotfr81#

$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

fjaof16o

fjaof16o2#

我本以为这是可行的(没有解释器访问,所以可能需要调整):

<?php

    class TestObject 
    {
        public $id;
        public $title;

        public function __construct($id, $title) {

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

            return true;
        }
    }

    $var = [
        new TestObject(11, 'Text 1'), 
        new TestObject(12, 'Text 2'),
        new TestObject(13, 'Text 3')
    ];
    $new_var = [];
    
    foreach ($var as $element) {
        $new_var[$element->id] = ['title' => $element->title];
    }
    
    print_r($new_var);

?>

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

相关问题