Php 更新数组
Php 更新数组,php,arrays,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 O
$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\u 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 )
)
如何做到这一点
谢谢。我原以为这会奏效(没有解释器访问权限,因此可能需要调整):
顺便说一句,您可能希望将变量命名约定更新为更有意义的内容。:-)
我假设你的对象中有更多的内容,你只想删除ID。如果你只想要标题,你不需要克隆到对象,只需设置
$new\u数组[$object->ID]=$object->title
就行了,给出错误:无法将stdClass类型的对象用作array@Ignatz-现在可以使用PHP访问机器-我已经修复了代码并提供了一个更完整的示例。顺便说一句,如果您有一个getter/setter,您应该将类变量更改为private,并在foreach迭代器中使用setter。@Ignatz-没问题-这就是stackoverflow.com的全部内容。:-)
<?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);
?>
$new_array = array();
foreach ($var as $object)
{
$temp_object = clone $object;
unset($temp_object->id);
$new_array[$object->id] = $temp_object;
}