php 更新数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3425074/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 09:41:14  来源:igfitidea点击:

Update an array

phparrays

提问by James

$varis an array:

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

Want to update it in two steps:

想分两步更新:

  • Get [ID]of each object and throw its value to position counter (I mean [0], [1], [2], [3])
  • Remove [ID]after throwing
  • 获取[ID]每个对象并将其值抛出到位置计数器(我的意思是[0], [1], [2], [3]
  • [ID]投掷后移除

Finally, updated array ($new_var) should look like:

最后,更新后的数组 ( $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 )
)

How to do this?

这该怎么做?

Thanks.

谢谢。

回答by Daniel Vandersluis

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

I'm making the assumption that there is more in your objects and you just want to remove ID. If you just want the title, you don't need to clone to the object and can just set $new_array[$object->id] = $object->title.

我假设您的对象中有更多内容,而您只想删除 ID。如果您只想要标题,则无需克隆到对象,只需设置$new_array[$object->id] = $object->title.

回答by John Parker

I'd have thought this would work (have no interpreter access, so it might require tweaking):

我原以为这会起作用(没有解释器访问权限,因此可能需要调整):

<?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);

?>

Incidentally, you might want to update your variable naming conventions to something more meaningful. :-)

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