1

I need to convert below array:-

Array
(
    [0] => stdClass Object
        (
            [id] => 
            [risk_reference] => 
            [risk_version] => 
            [bsi] => 10.00
        )

)

to below array:-

Array
(
     [id] => 
     [risk_reference] => 
     [risk_version] => 
     [bsi] => 10.00

)

I tried to do it by typecasting. But It didn't give me the output. I also checked this link

For Above $result = (array)($array[0]) works fine for me.

But if I have the below then what will I do?

Array
(
    [0] => stdClass Object
        (
            [id] => 
            [risk_reference] => 
            [risk_version] => 
            [bsi] => 10.00
        )
    [1] => stdClass Object
        (
            [id] => 
            [risk_reference] => 
            [risk_version] => 
            [bsi] => 20.00
        )

)
Community
  • 1
  • 1
Ripa Saha
  • 2,532
  • 6
  • 27
  • 51
  • 4
    `$result = (array)($array[0])`. You take the element with key `0` and cast it to array, there's nothing extraordinary going on. – Jon Feb 06 '14 at 09:47
  • Yes @Jon it really did my job. Thanks for this excellent solutions. But 1 question. If I have more than one object element then what will I do? – Ripa Saha Feb 06 '14 at 09:55
  • 1
    I can't answer that with confidence because you haven't said what result you will be expecting. Why not edit the question and give an example for that case too? This will allow people to help you better. – Jon Feb 06 '14 at 09:57
  • @Jon Your first answer is great for me. For my second question - I'm editing the question. – Ripa Saha Feb 06 '14 at 10:01

3 Answers3

1

Try this

$array = (array)($array[0]);
rccoros
  • 590
  • 9
  • 19
0

try this

$yourArray = array();
$i=0;
foreach ($yourObject as $key => $value) {
    $yourArray[$i]['id'] = $value->id;
    $yourArray[$i]['risk_reference'] = $value->risk_reference;
    $yourArray[$i]['risk_version'] = $value->risk_version;
    $yourArray[$i]['bsi'] = $value->bsi;
    $i+=1;
}
print_r($yourArray);
Satish Sharma
  • 9,547
  • 6
  • 29
  • 51
0

http://php.net/get_object_vars

Gets the accessible non-static properties of the given object according to scope.

Returns an associative array of defined object accessible non-static properties for the specified object in scope. If a property has not been assigned a value, it will be returned with a NULL value.

roninblade
  • 1,882
  • 15
  • 15