2014-07-26 41 views
0

我有子阵的排列:转换阵列子阵一个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)); 

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

回答

1

试试这个:

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

Demo

0

我认为你正在寻找这个

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

,并内置JSON $object = json_decode(json_encode($array), FALSE);使用..它所有的子阵列转换成对象..

如果这不是答案哟ü预计请在下面评论

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

让我知道它的工作。

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 
     ) 

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