我试图操纵多级类别树的结果,动态地给我一个如下所示的对象数组:
Array(
[0] => stdClass Object
(
[id] => 1
[children] => Array
(
[0] => stdClass Object
(
[id] => 2
)
[1] => stdClass Object
(
[id] => 3
)
)
)
[1] => stdClass Object
(
[id] => 9
)
[2] => stdClass Object
(
[id] => 4
[children] => Array
(
[0] => stdClass Object
(
[id] => 8
)
[1] => stdClass Object
(
[id] => 5
[children] => Array
(
[0] => stdClass Object
(
[id] => 6
)
[1] => stdClass Object
(
[id] => 7
)
)
)
)
))
它基本上告诉我们对象的id以及它是否有任何子节点。非常类似于Wordpress中的菜单构建器。
我想要做的是将这个数组转换为一个新的2级数组,如下所示:
Array(
[0] => Array
(
[0] => 1
[1] => 9
[2] => 4
)
[1] => Array
(
[0] => 2
[1] => 3
)
[4] => Array
(
[0] => 8
[1] => 5
)
[5] => Array
(
[0] => 6
[1] => 7
))
第一级的第一个键([0])将是没有父母的ID。所以ids 1,9和4是主要类别。子序列将是那些父母。因此,id 1有2和3作为子项,id 4有8和5作为子项,依此类推。
我很难搞清楚这一点。 感谢您提前提供任何帮助!
答案 0 :(得分:0)
使用递归函数可以实现这样的树结构展平。这是一个适用于您的树的示例。
function flatten($array_of_objects, $key = 0, &$result = []) {
// iterate the objects in the array
foreach ($array_of_objects as $object) {
// add each object's id to the result
$result[$key][] = $object->id;
// if the object has children, make the recursive call on that array
if (isset($object->children)) {
flatten($object->children, $object->id, $result);
}
}
return $result;
}
答案 1 :(得分:0)
export default class App extends React.Component {
state = {
fontLoaded: false,
};
async componentDidMount() {
await Font.loadAsync({
'helvetica': helveticaFont,
'roboto-condensed-light': robotoCondensedLight,
'roboto-condensed-regular': robotoCondensedRegular,
'roboto-condensed-bold': robotoCondensedBold,
});
this.setState({ fontLoaded: true });
}
render() {
return (
<View >
{
this.state.fontLoaded ? (
<SignIn></SignIn>
) : null
}
</View>
);
}
}