0

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));
6
  • You want your array to become an object, or better a collection of nested objects? Commented Aug 25, 2012 at 17:52
  • @moonwave99 Yes, json_encode for assoc array array('foo' => 'bar') return {"foo": "bar"} which become an object when you use json_decode('{"foo": "bar"}') so instead of $array['foo'] you access it via $array->foo - json_decode create instance of stdClass Commented Aug 25, 2012 at 17:57
  • Anyway, why don't you just store your data object-wise the first time, without passing for associative arrays? Commented Aug 25, 2012 at 18:19
  • Becasue php don't have syntax for creating objects like JSON in javascript and I would need to use something like like $this->config = new stdClass(); $admin = new stdClass(); $admin->user = 'admin'; $admin->password = $password; $this->config->users = array($admin); ... I prefer one extression. I post solution to this. Commented Aug 25, 2012 at 18:34
  • But php has classes! Just define a User class and provide a constructor: you will come with something like new User('admin', $password). Commented Aug 25, 2012 at 18:37

2 Answers 2

1

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;
    }
}
?>
Sign up to request clarification or add additional context in comments.

2 Comments

It's ok, but it gets rid of numeric indexed arrays [e.g. the users array in example given], which should stay as being collections of objects - just check that $name is not numeric.
@moonwave99 yes it should check if is_integer(array_keys($array)[0]) and then use return array_map('arrayToObject', $array);
0

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

2 Comments

By the way, you don't need to do this - just cast your array to object: (object)($this -> config) to obtain what your custom function does.
@moonwave99 I didn't know that you can cast to functions. But cast is not recursive second function will create object only from first array. But anyway I decide to drop this array to objec thing.

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.