如何在PHP中创建嵌套对象

时间:2013-11-26 07:06:47

标签: php

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

var_dump($array);

我想学习如何使用stdClass函数获得相同的结果,不希望在每个数组之前使用(object),转换导致某些资源,我知道json_encodejson_decode可以做到,只想了解stdClass如何制作嵌套结构。

2 个答案:

答案 0 :(得分:2)

json_encode()有一个技巧可以轻松搞定:

$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));

更新

如果您不想使用JSON函数,则可以递归处理数组,例如:

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

答案 1 :(得分:0)

此课程位于: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';
    }
}

用法:

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

var_dump($a);

$o = new RecursiveArrayObject($a);

var_dump($o);

收率:

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)