【发布时间】:2022-01-03 07:11:35
【问题描述】:
我正在尝试转换格式如下的数组:
object(Categories_store_tree)#519 (1) {
["list_of_sections":"Categories_store_tree":private]=> array(5) {
["id"]=> int(1)
["name"]=> string(11) "Main Store"
["parent_id"]=> NULL
["children"]=> array(2) {
[0]=> array(5) {
["id"]=> int(2)
["name"]=> string(4) "Food"
["parent_id"]=> int(1)
["children"]=> array(0) { }
}
[1]=> array(5) {
["id"]=> int(3)
["name"]=> string(14) "Electronics"
["parent_id"]=> int(1)
["children"]=> array(2) {
[0]=> array(5) {
["id"]=> int(4)
["name"]=> string(8) "Headphones"
["parent_id"]=> int(3)
["children"]=> array(0) { }
}
[1]=> array(5) {
["id"]=> int(5)
["name"]=> string(5) "Smartphones"
["parent_id"]=> int(3)
["children"]=> array(0) { }
}
}
}
}
}
}
到这个数组结构:
object(Categories_store_tree)#964 (1) {
["list_of_sections":"Categories_store_tree":private]=> array(5) {
[0]=> array(4) {
["id"]=> int(1)
["name"]=> string(11) "Main Store"
["parent_id"]=> NULL
}
[1]=> array(4) {
["id"]=> int(2)
["name"]=> string(4) "Food"
["parent_id"]=> int(1)
}
[2]=> array(4) {
["id"]=> int(3)
["name"]=> string(14) "Electronics"
["parent_id"]=> int(1)
}
[3]=> array(4) {
["id"]=> int(4)
["name"]=> string(8) "Headphones"
["parent_id"]=> int(3)
}
[4]=> array(4) {
["id"]=> int(5)
["name"]=> string(5) "Smartphones"
["parent_id"]=> int(3)
}
}
}
目前我正在手动操作,但我的想法是使其自动化。我试过这段代码,但它返回一个空数组,我也试过一个函数,但我卡了几天,不知道该怎么办。
$clean_array = array();
$cont = 0;
foreach ( $new_tree as $key => $value ) {
if ( is_array( $value ) ) {
$cont++;
foreach ( $value as $key1 => $value1 ) {
if ( is_array( $value1 ) ) {
$cont++;
foreach ( $value1 as $key2 => $value2 ) {
$clean_array[$cont][$key2] = $value2;
}
} else {
$clean_array[$cont][$key1] = $value1;
}
}
} else {
$clean_array[$cont][$key] = $value;
}
}
【问题讨论】:
-
那不是数组,是对象。