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
        )

)
4
  • 4
    $result = (array)($array[0]). You take the element with key 0 and cast it to array, there's nothing extraordinary going on. Commented Feb 6, 2014 at 9: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? Commented Feb 6, 2014 at 9: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. Commented Feb 6, 2014 at 9:57
  • @Jon Your first answer is great for me. For my second question - I'm editing the question. Commented Feb 6, 2014 at 10:01

3 Answers 3

1

Try this

$array = (array)($array[0]);
Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.