我有一个多维数组,我想运行一个循环,所以我可以单独插入我的数据库。多维数组可以具有无限多个深度。这是它的样子:
Array
(
[0] => Array
(
[slug] => item-slug-1
[name] => Item 1
[id] => 1
[children] => Array
(
[0] => Array
(
[slug] => item-slug-2
[name] => Item 2
[id] => 2
[children] => Array
(
[0] => Array
(
[slug] => item-slug-3
[name] => Item 3
[id] => 3
[children] => Array
(
[0] => Array
(
[slug] => item-slug-4
[name] => Item 4
[id] => 4
)
[1] => Array
(
[slug] => item-slug-5
[name] => Item 5
[id] => 5
)
)
)
)
)
)
)
)
我想将上面的代码格式化为一个我可以像这样轻松循环的数组:
foreach($categories as $category){
$data = array(
'name' => $category['name'],
'slug' => $category['slug'],
'parent' => $category['parent'],
);
update_category( $category['id'], $data );
}
非常感谢任何帮助。
答案 0 :(得分:0)
function walk_and_update($data) {
if( is_array($data) ) {
foreach( $data as $key => $row ) {
update_category( $row['id'], array(
'name' => $row['name'],
'slug' => $row['slug'],
'parent' => $row['parent'],
) );
if( isset($row['children']) ) {
walk_and_update($row['children']);
}
}
}
}