简而言之,我开始了我的问题,
我只是读取json文件,
[{"FirstCategory":"Bath","SecondCategory":"Bath Accessories","ThirdCategory":""}, {"FirstCategory":"Bath","SecondCategory":"Faucets","ThirdCategory":""},{"FirstCategory":"Bath","SecondCategory":"Fixtures","ThirdCategory":""},{"FirstCategory":"Bath","SecondCategory":"Vanities","ThirdCategory":""},{"FirstCategory":"Building Materials","SecondCategory":"Concrete","ThirdCategory":""},{"FirstCategory":"Building Materials","SecondCategory":"Fencing","ThirdCategory":""},{"FirstCategory":"Building Materials","SecondCategory":"Gypsum","ThirdCategory":""},{"FirstCategory":"Building Materials","SecondCategory":"Insulation","ThirdCategory":""},{"FirstCategory":"Building Materials","SecondCategory":"Insulssdation","ThirdCategory":""}]
并尝试转换为数组
Array
(
[Bath] => Array
(
[Bath Accessories] => Array
(
[0] => test
)
[Faucets] => Array
(
[0] => test1
[1] => test2
)
)
)//sorry i have used PHP for simple formatting the array.
我花了很多时间在这个东西上,但我无法成功,请帮助我。
My javascript code : (not working.)
var FirstCategory = [];
var SecondCategory = [];
var ThirdCategory = [];
$.getJSON('tree.json', function(data) {
var dataObj = new Array();
$.each(data,function(i){
dataObj[data[i].FirstCategory] = new Array();
if([data[i].SecondCategory] in dataObj[data[i].FirstCategory])
dataObj[data[i].FirstCategory][data[i].SecondCategory] = data[i].SecondCategory;
else
dataObj[data[i].FirstCategory][data[i].SecondCategory] = new Array();
dataObj[data[i].FirstCategory][data[i].SecondCategory][data[i].ThirdCategory] = new Array();
});
console.log(dataObj);
/*
$.each(data,function(i){
if (FirstCategory == '') {
FirstCategory.push(data[i].FirstCategory);
}
else
{
if(!FirstCategory.contains(data[i].FirstCategory))
{
//root
FirstCategory.push(data[i].FirstCategory);
}
else
{
//------- second level category -------//
if (SecondCategory == '') {
SecondCategory.push(data[i].SecondCategory);
}
else
{
if(!SecondCategory.contains(data[i].SecondCategory))
{
SecondCategory.push(data[i].SecondCategory);
}
else
{
ThirdCategory.push(data[i].ThirdCategory);
}
}
}
}
});
*/
});
Array.prototype.contains = function(obj) {
var i = this.length;
while (i--) {
if (this[i] == obj) {
return true;
}
}
return false;
}
提前致谢。