Skip to content

Instantly share code, notes, and snippets.

@muzfr7
Last active February 6, 2018 09:44

Revisions

  1. muzfr7 revised this gist Feb 6, 2018. No changes.
  2. muzfr7 revised this gist Feb 6, 2018. No changes.
  3. muzfr7 created this gist Feb 6, 2018.
    35 changes: 35 additions & 0 deletions ConvertMultidimensionalArrayToObject.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,35 @@
    <?php

    // A multi-dimensional array
    $user = [
    'firstname'=>'Muzafar',
    'lastname'=>'Jatoi',
    'contacts'=>[
    [
    'mobile'=>'0500000000',
    'email'=>'john@gmail.com',
    ],
    [
    'mobile'=>'03000000000',
    'email'=>'doe@gmail.com',
    ]
    ]
    ];

    // Converts given multi-dimensional array into object recursively
    function arrayToObject(array $arr) {
    $obj = new stdClass();
    foreach ($arr as $key=>$value) {
    if (is_array($value)) {
    $obj->$key = arrayToObject($value);
    }else{
    $obj->$key = $value;
    }
    }
    return $obj;
    }

    $userObj = arrayToObject($user);

    echo $userObj->firstname; // Muzafar
    echo $userObj->contacts->{0}->mobile; // 0500000000