我有一个数组,它看起来像
Array
(
[438044691:maincategoryone] => Array
(
[0] => Array
(
[id] => 438044692
[name] => main category one item one
[category] => Array
(
[2] => Array
(
[id] => 4380444456
[name] => main category one item one - sub
)
)
)
[1] => Array
(
[id] => 438044693
[name] => main category one item two
)
)
[438044701:maincategorytwo] => Array
(
[0] => Array
(
[id] => 438044702
[name] => main category two item one
)
)
[438044709:maincategorythree] => Array
(
[0] => Array
(
[id] => 438044710
[name] => main category three item one
)
[1] => Array
(
[id] => 438044711
[name] => main category three item two
)
)
)如何在PHP中遍历这些数据并将数据存储在同一个表(MYSQL)中的父-子-孙关系中。
另外,一个示例查询可以在插入后按顺序(父-子-孙)检索数据。
希望我的问题说得通。如果没有,请原谅,但我会给你更多的信息。
非常感谢。
发布于 2010-06-23 17:36:37
我建议在您的mySQL表中为父级提供一个引用键,如下所示:
CREATE TABLE categories (id INTEGER, name VARCHAR(32), parent INTEGER)然后在PHP代码中,您有一个树模型,读取id索引数组中的所有项,然后将其组装到树中。
$q = mysql_query("SELECT * FROM categories");
$n = mysql_num_rows($q);
$items = array();
while($item = mysql_fetch_assoc($q))
$items[$item['id']] = $item;
foreach($items as $item)
$items[$item['parent']]['category'] = $item;
print_r($items);为了从树中读取值,我将使用一个递归函数:
function add_to_tree($items, $tree_part, $parent) {
$tree_part['parent'] = $parent;
$items.push($tree_part);
foreach($tree_part['categories'] as $child)
add_to_tree($items, $child, $tree_part['id']);
}然后,您只需创建一个空数组,填充它并按顺序读取值。
$items = array();
add_to_tree($items, $tree);
foreach($items as $item)
mysql_query("INSERT INTO categories VALUES('{$item['id']}', '{$item['name']}', '{$item['parent']}');当然,您必须处理特殊情况,如根对象和缺少链接,这在前面的代码中是不受支持的。
发布于 2010-06-23 17:39:21
您可以通过创建一个包含3列id、name、parentid的表来完成此操作
您可以使用PHP函数遍历数组并在执行时插入行(或者构建一个array_walk查询以便稍后执行):
$myArray = ......
array_walk($myArray , 'insertInDb', null);
function insertInDb($item, $key, $parent_id) {
if (is_null($parent_id)) {
$sql = sprintf('INSERT INTO myTable (`id`, `name`, `parentid`) VALUES (%d, "%s", NULL)', $item['id'], $item['name']);
} else {
$sql = sprintf('INSERT INTO myTable (`id`, `name`, `parentid`) VALUES (%d, "%s", %d)', $item['id'], $item['name'], $parent_id);
}
array_walk($item['category'] , 'insertInDb', $item['id']);
}https://stackoverflow.com/questions/3100391
复制相似问题