我有一个嵌套的拖放列表,它返回json formattet字符串。我可以在这个字符串上运行php serialize,json_decode等。但我坚持在DB中保存层次结构。
返回输出的示例:
[{ “ID”:1, “孩子”:[{ “ID”:2, “孩子”:[{ “ID”:4},{ “ID”:7},{ “ID”:8 }]},{ “ID”:3}]},{ “ID”:5},{ “ID”:6}]
...或...
Array ( [0] => Array ( [id] => 1 [children] => Array ( [0] => Array ( [id] => 2 [children] => Array ( [0] => Array ( [id] => 4 ) [1] => Array ( [id] => 7 ) [2] => Array ( [id] => 8 ) ) ) [1] => Array ( [id] => 3 ) ) ) [1] => Array ( [id] => 5 ) [2] => Array ( [id] => 6 ) )
我想将此输出保存为DB结构,如下所示:
CREATE TABLE IF NOT EXISTS `menu` ( `id` int(11) NOT NULL AUTO_INCREMENT, `rang` int(11) NOT NULL, `parent_id` int(11) NOT NULL, `name` varchar(256) NOT NULL, `description` varchar(256) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=9 ;
有什么想法吗?
答案 0 :(得分:1)
我会这样做:
<?php
$jsonString = '[{"id":1,"children":[{"id":2,"children":[{"id":4},{"id":7},{"id":8}]},{"id":3}]},{"id":5},{"id":6}]';
$jsonArray = json_decode($jsonString, true);
function parseJsonArray($jsonArray, $parentID = 0)
{
$return = array();
foreach ($jsonArray as $subArray) {
$returnSubSubArray = array();
if (isset($subArray['children'])) {
$returnSubSubArray = parseJsonArray($subArray['children'], $subArray['id']);
}
$return[] = array('id' => $subArray['id'], 'parentID' => $parentID);
$return = array_merge($return, $returnSubSubArray);
}
return $return;
}
var_dump(parseJsonArray($jsonArray));
你应该得到这样的数组:
Array (
[0] => Array (
[id] => 1
[parentID] => 0
)
[1] => Array (
[id] => 2
[parentID] => 1
)
// ETC.
)
答案 1 :(得分:0)
您在mysql German Tutorial for Nested Sets上设置了嵌套集模型,这可能是最好的方法,或者您可以将请求字符串存储在数据库中(但要注意,您不能在mysql端执行任何操作。 ..)
答案 2 :(得分:0)
我假设您使用JSON-Data中的ID作为数据库中的主键。所以你不必处理LAST_INSERT_ID。
function storeTree(array $treeList) {
// Optional: Start DB-Transaction
try {
storeList($treeList);
// Optional: Commit DB-Transaction
} catch(Exception $e) {
// Optional: Rollback DB-Transaction
}
}
function storeList(array $list, $parentId=null) {
foreach($list as $child) {
storeChild($child, $parentId);
}
}
function storeChild(array $childData, $parentId=null) {
$childId = $childData['id'];
$children = isset($childData['children']) ? (array) $childData['children'] : array();
// Add a new dataset: `id` = $childId, `parent_id` = $parentId
storeList($children, $childId);
}
storeTree($youJsonData);
此代码未经过测试,可能包含错误......