我正在尝试将以下数组更改为几乎平坦的数组。所以id 4将在数组的第一级,如id 6和5,但仍然有自己的索引,所以我可以告诉哪个页面是哪个。但是和他们现在的顺序相同。我认为解决方案将是某种递归PHP函数,但我不知道如何做到这一点。
Array
(
[0] => Array
(
[id] => 2
[identifier] => External URL
[parent] => 0
[sortOrder] => 1
[depth] => 0
)
[1] => Array
(
[id] => 3
[identifier] => First Team
[parent] => 0
[sortOrder] => 2
[depth] => 0
[children] => Array
(
[0] => Array
(
[id] => 4
[identifier] => League tables
[parent] => 3
[sortOrder] => 0
[depth] => 1
[children] => Array
(
[0] => Array
(
[id] => 6
[identifier] => British and Irish Cup Tables
[parent] => 4
[sortOrder] => 24
[depth] => 2
)
[1] => Array
(
[id] => 5
[identifier] => Greene King IPA Championship
[parent] => 4
[sortOrder] => 25
[depth] => 2
)
)
)
)
)
[2] => Array
(
[id] => 1
[identifier] => Home
[parent] => 0
[sortOrder] => 25
[depth] => 0
)
)
答案 0 :(得分:0)
<?php
$data = [
[
'id' => 1,
'name' => 'one',
'children' =>
[
[
'id' => 2,
'name' => 'two',
'children' =>
[
[
'id' => 4,
'name' => 'four'
]
]
],
[
'id' => 3,
'name' => 'three',
'children' =>
[
[
'id' => 5,
'name' => 'five'
]
]
]
]
],
[
'id' => 6,
'name' => 'six'
]
];
$stanley = [];
$flatten = function(array $data) use (&$flatten, &$stanley) {
foreach($data as $k => $v) {
if(isset($v['children'])) {
$flatten($v['children']);
unset($v['children']);
}
$stanley[] = $v;
}
};
$flatten($data);
var_export($stanley);
输出:
array (
0 =>
array (
'id' => 4,
'name' => 'four',
),
1 =>
array (
'id' => 2,
'name' => 'two',
),
2 =>
array (
'id' => 5,
'name' => 'five',
),
3 =>
array (
'id' => 3,
'name' => 'three',
),
4 =>
array (
'id' => 1,
'name' => 'one',
),
5 =>
array (
'id' => 6,
'name' => 'six',
),
)
答案 1 :(得分:0)
我找到了解决方案!我构建了一个递归的PHP函数,它利用深度索引来跟踪每个项目的哪个级别,同时仍然保持阵列平坦(ish)。
static class Customer{
String name;
int salary;
int age;
public Customer(String name, int salary, int age) {
this.name = name;
this.salary = salary;
this.age = age;
}
}
public static void main(String[] args) {
ArrayList<Customer> data = new ArrayList<Customer>(){{add(new Customer("x",100,20));add(
new Customer("y",200,30));add(new Customer("z",300,40));}};
for(Customer c:data){
System.out.println(c.name+" _ "+c.salary+" - "+c.age);
}
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
for(Customer c :data){
dataset.addValue(c.salary, "low", "");
}
//Cont'd other JFreechart codes ...
}