我需要用例如编码一个多维数组CJavaScript 或 CJSON,但我需要避免使用 PHP 数组键。
假设数据结构如下
$dataTree = array(
'39'=>array(
'label' => 'node1',
'children' => array(
'42'=>array('label' => 'child1'),
'44'=>array('label' => 'child2'),
),
),
'40'=>array(
'label' => 'node2',
)
);
我需要获得以下输出(在 Javascript 中):
var data = [
{
label: 'node1',
children: [
{ label: 'child1' },
{ label: 'child2' }
]
},
{
label: 'node2',
children: [
{ label: 'child3' }
]
}
];
有什么办法吗?
最佳答案
使用此代码。
<?php
$dataTree = array(
'39'=>array(
'label' => 'node1',
'children' => array(
'42'=>array('label' => 'child1'),
'44'=>array('label' => 'child2'),
),
),
'40'=>array(
'label' => 'node2',
'children' => array(
'42'=>array('label' => 'child3'),
),
)
);
$res = array();
foreach( $dataTree as $val)
{
$temp_ch = array();
foreach($val["children"] as $ch)
$temp_ch[]=$ch;
$val["children"] = $temp_ch;
$res[] = $val;
}
echo json_encode($res);
?>
关于javascript - Yii 为 JavaScript 编码数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20718485/