SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Member
    Join Date
    Jun 2011
    Posts
    2
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Question Convert Oject into array with keys unchanged

    Hi ,

    I have an object array '$churches' like this :


    PHP Code:
    Array
    (
        [
    0] => stdClass Object
            
    (
                [
    church_id] => 1
                
    [title] => Me
            
    )

        [
    1] => stdClass Object
            
    (
                [
    church_id] => 2
                
    [title] => Alwin
            
    )


    Now I need to convert these into an array in which the church_id is the index and title as element. Please let me know how can I do this. I think this may be easy but nothing is flashing through my head. I have used foreach and array_merge. But it is not seems to be working. It will be hlpful if someone can help me ASAP as it is little urgent.

  2. #2
    Twitter: @AnthonySterling silver trophy AnthonySterling's Avatar
    Join Date
    Apr 2008
    Location
    North-East, UK.
    Posts
    6,111
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    Welcome to Sitepoint alwinaugustin.

    You can cast the object as an array.

    PHP Code:
    <?php
    $obj 
    = new stdClass;
    $obj->church_id 1;
    $obj->title 'Me';

    $arr = (array)$obj;

    print_r($arr);

    /*
      Array
      (
        [church_id] => 1
        [title] => Me
      )
    */
    @AnthonySterling: I'm a PHP developer, a consultant for oopnorth.com and the organiser of @phpne, a PHP User Group covering the North-East of England.

  3. #3
    SitePoint Enthusiast
    Join Date
    Jan 2011
    Posts
    45
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Do you mean something like -

    Code PHP:
    $churches_new = array();
    foreach( $churches as $array )
    {
    	$churches_new[$array['church_id']] = $array['title'];
    }
     
    unset( $churches );
     
    $churches = $churches_new;
    unset( $churches_new );


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •