0
我有一個多維數組,我想創建成一個對象,然後我可以輸出xml和json。php多維數組遞歸地插入一個對象
我很難得到我的頭,如何遞歸地做到這一點。我看過很多可以在這裏找到的多維帖子,但我仍然陷入困境。
我在做什麼錯?
class Dataset
{
public $name;
public $attr = array();
public $children = array();
function __construct($name){
$this->name = $name;
}
function addAttr($attr){
$this->attr[] = $attr;
}
function addChildren($children){
$this->children[] = $children;
}
}
$jazzy = Array(
name => 'aaa',
attr => Array(
id => 123
),
children => Array(
Array(
name => 'name',
attr => Array(),
children => Array(
'www'
),
),
Array(
name => 'websites',
attr => Array(),
children => Array(
Array(
name => 'website',
attr => Array(
id => 456,
class => 'boom'
),
children => Array(
Array(
name => 'url',
attr => Array(),
children => Array(
'www.test.com'
)
)
)
),
Array(
name => 'website',
attr => Array(
id => 123,
class => "boom"
),
children => Array(
Array(
name => 'url',
attr => Array(),
children => Array(
'www.example.com'
)
)
)
)
)
)
)
);
我期待創建此輸出
<aaa id="123">
<name>www</name>
<websites>
<website id='456' class="boom">
<url>www.test.com</url>
</website>
<website id='123 class="boom">
<url>www.example.com</url>
</website>
</websites>
</aaa>
我的代碼
function arrayToDataset($array, $node){
foreach ($array as $key => $value) {
$name = $array['name'];
$attr = $array['attr'];
$children = $array['children'];
if($key == "name"){
$name = $value;
$node->addName($name);
}
elseif($key == "attr"){
$attr = $value;
$node->addAttr($attr);
}
elseif($key == "children")
{
$children = $value;
$newNode = new Dataset();
foreach($children as $k => $v)
{
$newNode = $node->addChildren($v);
}
return arrayToDataset($children, $newNode);
}
}
}
$node = new Dataset();
$thing = arrayToDataset($jazzy, $node);
print_r($thing);
看看的[array_walk_recursive()](http://php.net/manual/en/function.array-walk-recursive.php )功能。 – coderodour
*此功能只訪問葉節點* – Tristanisginger
$ jazzy數組格式不正確 - 不知道如果這是你的代碼的副本,但應該引用密鑰。如果我們可以複製/粘貼代碼,它會更容易幫助... – RichGoldMD