Convert Oject into array with keys unchanged

Hi ,

I have an object array ‘$churches’ like this :

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.

Welcome to Sitepoint alwinaugustin. :slight_smile:

You can cast the object as an array.


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

$arr = (array)$obj;

print_r($arr);

/*
  Array
  (
    [church_id] => 1
    [title] => Me
  )
*/

Do you mean something like -


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

unset( $churches );

$churches = $churches_new;
unset( $churches_new );