3
$array = (object)array(
    'name' => 'David',
    'friends' => (object)array(
        (object)array('name' => 'Max'),
        (object)array('name' => 'Jian')
    )
);

var_dump($array);

I want to learn how to use stdClass function to get the same result, don't want to use (object) before each array, convert cause some resource, and I know json_encode and json_decode can make it, just want to learn how stdClass make nested structure.

4
  • How much PHP have you programmed? Commented Nov 26, 2013 at 7:09
  • Simplest solution (aside from casting to object): Create an array, json_encode it, and json_decode the resulting JSON. :P Next closest: Create an array and then recursively objectify it. Commented Nov 26, 2013 at 7:10
  • What do you mean? I mean @EricHerlitz Commented Nov 26, 2013 at 7:10
  • You can't. If the json hack bothers you, wrap it in another function incase you find a better implementation later. Commented Nov 26, 2013 at 7:13

2 Answers 2

3

There's a trick with json_encode() to easily get this:

$array = array(
  'foo' => array('bar'=>'a', 'baz'=>'b'),
  'feo' => 'bee',
  'boo' => array('a'=>array('x', 'y'), 'b'=>array('z'))
);


$object = json_decode(json_encode($array));

Update

If you don't want to use JSON function, you can handle your array recursively, like:

function getStdObject(array $data)
{
   foreach($data as &$item)
   {
      if(is_array($item))
      {
         $item = getStdObject($item);
      }
   }
   return (object)$data;
}

$array = array(
  'foo' => array('bar'=>'a', 'baz'=>'b'),
  'feo' => 'bee',
  'boo' => array('a'=>array('x', 'y'), 'b'=>array('z'))
);
$object = getStdObject($array));
Sign up to request clarification or add additional context in comments.

Comments

1

This class is available at: http://php.net/manual/en/arrayobject.construct.php#111192

/**
 * @author Iltar van der Berg
 * @version 2.0.0
 */
class RecursiveArrayObject extends ArrayObject
{
    /**
     * overwrites the ArrayObject constructor for 
     * iteration through the "array". When the item
     * is an array, it creates another self() instead
     * of an array
     * 
     * @param Array $array data array
     */
    public function __construct(Array $array)
    {    
        foreach($array as $key => $value) {
            if(is_array($value)){
                $value = new static($value);
            }
            $this->offsetSet($key, $value);
        }
    }

    /**
     * returns Array when printed (like "echo array();")
     * instead of an error
     *
     * @return string
     */
    public function __ToString()
    {
        return 'Array';
    }
}

Usage:

$a = array(
    'one' => array(
            'hello','world'
        ),
    'two' => array(
            'lorem','ipsum'
        )
);

var_dump($a);

$o = new RecursiveArrayObject($a);

var_dump($o);

Yields:

array (size=2)
  'one' => 
    array (size=2)
      0 => string 'hello' (length=5)
      1 => string 'world' (length=5)
  'two' => 
    array (size=2)
      0 => string 'lorem' (length=5)
      1 => string 'ipsum' (length=5)

object(RecursiveArrayObject)[1]
  public 'one' => 
    object(RecursiveArrayObject)[2]
      string 'hello' (length=5)
      string 'world' (length=5)
  public 'two' => 
    object(RecursiveArrayObject)[3]
      string 'lorem' (length=5)
      string 'ipsum' (length=5)

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.