jcubic
jcubic

Reputation: 66490

How to create nested object from nested arrays in php

I have code like this, that initialize config

    $this->config = array(
        'users' => array(
            array('name' => 'admin',
                  'password' => $password
            )
        ),
        'tokens' => array(),
        'sessions' => array(),
    );

that I'm saving to a file using json_encode($this->config) and later I load it using

json_decode(file_get_contents('file.json'));

it create nested objects, I would like to have this nested object when I initialize and the config, is there a way to create this nested object other then this?

$this->config = json_decode(json_encode($this->config));

Upvotes: 0

Views: 2726

Answers (2)

jcubic
jcubic

Reputation: 66490

I decide to use this function instead

function object($array) {
    $object = new stdClass();
    foreach ($array as $k => $v) {
        $object->$k = $v;
    }
    return $object;
}

and explicitly call it for assoc arrays

$this->config = object(array(
    'users' => array(
        object(array(
            'name' => 'admin',
            'password' => $password
        ))
    ),
    'tokens' => array(),
    'sessions' => array(),
));

EDIT recursive code

function is_assoc($array) {
    if (!is_array($array)) {
        return false;
    } else {
        $keys = array_keys($array);
        return !is_numeric($keys[0]);
    }
}

function object($array) {
    if (is_assoc($array)) {
        $object = new stdClass();
        foreach ($array as $k => $v) {
            $object->$k = object($v);
        }
        return $object;
    } else {
        return $array;
    }
}

Upvotes: 0

Arun Poudel
Arun Poudel

Reputation: 627

You can alternatively use this function

<?php
function arrayToObject($array) {
    if(!is_array($array)) {
        return $array;
    }

    $object = new stdClass();
    if (is_array($array) && count($array) > 0) {
      foreach ($array as $name=>$value) {
         $name = strtolower(trim($name));
         if (!empty($name)) {
            $object->$name = arrayToObject($value);
         }
      }
      return $object;
    }
    else {
      return FALSE;
    }
}
?>

Upvotes: 1

Related Questions