Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to flatten multi dimensional object which is in fact array in php?

So, i have multi dimensional – multi object array which looks something like this(just a snippet):

array(1) {
  [0]=>
  object(Justimmo\Model\Realty)#14 (136) {
    ["id":protected]=>
    int(103xxx757)
    ["propertyNumber":protected]=>
    string(10) "3108xx6"
    ["title":protected]=>
    string(62) "Ruhige 3-Zimmer mit Freifläche in ..."
    ["teaser":protected]=>
    NULL
    ["proximity":protected]=>
    string(4) "Wien"
    ["description":protected]=>
    ["additionalCosts":protected]=>
       array(1) {
         ["betriebskosten"]=>
         object(Justimmo\Model\AdditionalCosts)#24 (8) {
           ["name":protected]=>
           string(14) "Betriebskosten"
           ["net":protected]=>
           float(140)
           ["gross":protected]=>
           float(154)
           ["vat":protected]=>
           float(10)
           ["vatType":protected]=>
           string(7) "percent"
           ["vatValue":protected]=>
           float(14)
           ["vatInput":protected]=>
           float(10)
           ["optional":protected]=>
           bool(false)
        }
    }
...........

How can i flatten it to be one dimensional array so i can process it further?

Thanks.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Does this do what you want?

function flatten_all($obj){
    $array = array();
    foreach( $obj as $key => $value ){
        if( is_object($value) || is_array($value) ){
            $temp_array = flatten_all((array)($value));
            foreach( $temp_array as $t_key => $t_value ){
                $array[$t_key] = $t_value;
            }
        }
        else{
            $array[$key] = $value;
        }
    }
    return $array;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading