开发者

Convert indexed array of objects to an associative array of objects using a column as the new first-level keys

$var is an array:

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

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

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.


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


Iterate the array of object and populate a new array of objects with the desired structure using the columnar data. I am manually casting the reduced payloads (containing a single property) as objects.

Code: (Demo)

$result = [];
foreach ($array as $obj) {
    $result[$obj->ID] = (object) ['title' => $obj->title];
}
var_export($result);

Or preserve the id column value, unset that property from the object, then push the mutated version of the object.

BUT be careful with this option because objects modify the original values in a foreach()! (Demo)

$result = [];
foreach ($array as $obj) {
    $id = $obj->ID;
    unset($obj->ID);
    $result[$id] = $obj;
}
var_export($result);

echo "\n---\n";

var_export($array);  // <-- notice how the original array has lost its id properties

@DanielVandersluis's answer does not suffer this mutation of the original array. Proof: https://3v4l.org/1ggB6

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜