tags:

views:

366

answers:

2
+4  Q: 

PHP new array()

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

+2  A: 

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. :-)

middaparka
Doesn't work, gives an error: Cannot use object of type stdClass as array
Happy
@Ignatz - Have access to a machine with PHP on now - I've fixed the code and provided a more complete example. Incidentally, if you have an getter/setter, you should change the class vars to private and use the setter within the foreach iterator.
middaparka
thanks man for your time
Happy
@Ignatz - No problem - that's what stackoverflow.com is all about. :-)
middaparka
+6  A: 
$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.

Daniel Vandersluis
+1 A neater solution than mine. :-)
middaparka