Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update an array

Tags:

arrays

php

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

like image 459
James Avatar asked Aug 06 '10 15:08

James


1 Answers

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

like image 133
Daniel Vandersluis Avatar answered Oct 10 '22 21:10

Daniel Vandersluis