Search code examples
phparraysobjectassociative-array

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.


Solution

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