我正在尝试创建一个包含三维的数组。 首先让我解释一下我的数据是如何产生的。 我目前的数据
Array
(
[0] => stdClass Object
([1] => A [2] => a [3] => *)
[1] => stdClass Object
([1] => A [2] => a [3] => $)
[2] => stdClass Object
([1] => B [2] => a [3] => %)
[3] => stdClass Object
([1] => B [2] => b [3] => @)
[4] => stdClass Object
([1] => B[2] => c[3] => x)
我想要的是什么:
Array
(
[0] => A(
[0] => a(
[0] => *
[1] => $
)
)
[1] => B
(
[0] => a(
[0] => %
)
[1] => b(
[0] => $
)
[2] => c(
[0] => x
)
)
首先,我必须删除重复的标题make数组,然后添加更多的数组值 所以到目前为止我已经完成了,不知道去哪里
代码:
$query = $this->db->get();
$raw_data = $query->result();
//$array = json_decode(json_encode($data), true);
$data = array();
echo "<pre>";
foreach ($raw_data as $key => $value) {
if (in_array($value->DEPT, $data) != 1) {
$data[] = $value->DEPT;
}
}
//for here no idea what to do
foreach ($raw_data as $key => $value) {
$d_key = array_search($value->DEPT, $data[$d_key]);
if (in_array($value->CAT, $data) != 1) {
$data[$d_key] = [$value->CAT];
}
}
print_r($data);
echo "</pre>";
我删除了重复新内容我想在主标题数组中添加子标题
答案 0 :(得分:1)
试试这个:
$raw_data = [
['A', 'a', '*'],
['A', 'a', '$'],
['B', 'a', '%'],
['B', 'b', '@'],
['B', 'c', 'x'],
];
$data = [];
foreach ($raw_data as $row) {
if (!array_key_exists($row[0], $data)) $data[$row[0]] = [];
if (!array_key_exists($row[1], $data[$row[0]])) $data[$row[0]][$row[1]] = [];
$data[$row[0]][$row[1]][] = $row[2];
}
print_r($data);
输出:
Array
(
[A] => Array
(
[a] => Array
(
[0] => *
[1] => $
)
)
[B] => Array
(
[a] => Array
(
[0] => %
)
[b] => Array
(
[0] => @
)
[c] => Array
(
[0] => x
)
)
)
它基本上只是为标题和子标题添加一个新的子数组(如果它还不存在),然后将子标题设置为标题和子标题的路径值