将带有子数组的数组转换为stdClass

时间:2014-07-26 08:49:59

标签: php arrays stdclass

我有一个包含子数组的数组:

$test = array("hello" => "world", "object" => array("bye" => "world"));

我想将其转换为对象:

$obj = (object) $test;

父数组变为对象,但子数仍为数组:

object(stdClass)[1]
  public 'hello' => string 'world' (length=5)
  public 'object' => 
    array (size=1)
      'bye' => string 'world' (length=5)

但我想得到这样的东西:

object(stdClass)[1]
  public 'hello' => string 'world' (length=5)
  public 'object' => 
    object(stdClass)[2]
      public 'bye' => string 'world' (length=5)

使用此代码可以达到:

$testObj = json_decode(json_encode($test));

但这是不好的做法。我怎样才能达到这个结果?

5 个答案:

答案 0 :(得分:3)

尝试这可能会有所帮助。

how to convert multidimensional array to object in php?

function convert_array_to_obj_recursive($a) {
if (is_array($a) ) {
    foreach($a as $k => $v) {
        if (is_integer($k)) {
            // only need this if you want to keep the array indexes separate
            // from the object notation: eg. $o->{1}
            $a['index'][$k] = convert_array_to_obj_recursive($v);
        }
        else {
            $a[$k] = convert_array_to_obj_recursive($v);
        }
    }

    return (object) $a;
}

// else maintain the type of $a
return $a; 
}

让我知道它是否有效。

答案 1 :(得分:1)

试试这个:

function cast($array) {
    if (!is_array($array)) return $array;
    foreach ($array as &$v) {
        $v = cast($v);
    }
    return (object) $array;
}
$result = cast($test);

Demo

答案 2 :(得分:1)

你可以通过这种方式,通过foreach和条件来做到这一点:

$array = array("hello" => "world", "object" => array("bye" => "world"));

foreach($array as $key => $val) {

    if(is_array($val)) {
        $aa[$key] = (object) $val; 
    }
    else {
        $aa[$key] = $val;
    }

    $obj  = (object) $aa;
}

echo "<pre>";
var_dump($obj);
echo "</pre>";

答案 3 :(得分:0)

我认为你正在寻找这个

$object = new stdClass();
foreach ($array as $key => $value)
{
    $object->$key = $value;
}

并在内置json $object = json_decode(json_encode($array), FALSE);中使用..它将所有子数组转换为对象..

如果这不是您期望的答案,请在下面发表评论

答案 4 :(得分:0)

function arrayToObject($arr) {
    if (is_array($arr)) 
        return (object) array_map(__FUNCTION__, $arr);

    else
        return $arr;
}

arrayToObject($test)的输出将是,

stdClass Object
(
    [hello] => world
    [object] => stdClass Object
        (
            [bye] => world
        )

)