Jump to content


Photo

i need help making an array out of an object


  • Please log in to reply
3 replies to this topic

#1 emehrkay

emehrkay
  • Staff Alumni
  • Advanced Member
  • 1,214 posts

Posted 16 March 2006 - 03:41 PM

i have this object
Array
(
    [0] => stdClass Object
        (
            [first_name] => Jennifer
            [last_name] => Masi
            [person_id] => 1309
        )

    [1] => stdClass Object
        (
            [first_name] => Roy
            [last_name] => Mc
            [person_id] => 2469
        )

)

now i want loop through that and put the person_id as the key and first & last names as the value. i tried array_push, but i dont think you can define what the key will be with that function. is there any way for me to do this?

my current line of thinking ($this->_data_contact is the object):
$con_count = count($this->_data_contact);
        
        $con_arr   = array($arr_val);
        for($i = 0; $i < $con_count; $i++){
            array_push ($con_arr, $this->_data_contact[$i]->person_id."=>".$this->_data_contact[$i]->first_name." ".$this->_data_contact[$i]->last_name);
        }

that only creates
[0]=>"id=>first last"
[1]=>"id=>first last"

#2 ober

ober
  • Staff Alumni
  • Advanced Member
  • 5,337 posts
  • LocationEast Coast, USA

Posted 16 March 2006 - 06:20 PM

Why can't you just set the keys normally?
for($i = 0; $i < $con_count; $i++)
      $con_arr[$this->_data_contact[$i]->person_id] = $this->_data_contact[$i]->first_name." ".$this->_data_contact[$i]->last_name;

By the way, it may be force of habit for some, but you don't need braces around a single-line for/if/while.

Info: PHP Manual


#3 emehrkay

emehrkay
  • Staff Alumni
  • Advanced Member
  • 1,214 posts

Posted 16 March 2006 - 07:27 PM

thanks ober you always come through in the clutch, like kobe or mj.

yeah i think the brackets is a habit, and i like to see my code done that way. oh, most importantly, its a standard at my job - lol

#4 ober

ober
  • Staff Alumni
  • Advanced Member
  • 5,337 posts
  • LocationEast Coast, USA

Posted 16 March 2006 - 07:43 PM

Glad to help :)

I know some people are forced to do it, but I know there are a lot of people that don't know you can skip them.

Info: PHP Manual





0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users