我需要根据时间将单个数组分为多个子数组.出现在数组键中,以便我告诉谁是父类别,谁不是.请注意,嵌套父母的数量没有限制.
另外,如果存在同名的子代,但如果其父代不同,则视为唯一.
我的源数组结构如下所示:
array (
'Test Parent 2>Test Child>Test Sub Child' =>
array (
'content_id_4' => NULL,
),
'Test Parent 3' =>
array (
'content_id_4' => NULL,
'content_id_5' => NULL,
),
'Test Parent>Test Child>Test Sub Child' =>
array (
'content_id_3' => NULL,
),
'Test Parent 2 with No Kids' =>
array (
'content_id_3' => NULL,
),
'Collections>Sports' =>
array (
'content_id_2' => NULL,
'content_id_22' => NULL,
),
'Collections' =>
array (
'content_id_2' => NULL,
'content_id_22' => NULL,
'content_id_6' => NULL,
),
'Collections>Charity' =>
array (
'content_id_6' => NULL,
),
)
在上面的示例中,“测试父对象”>“测试子对象”>“测试子子对象”将意味着存在父子类别“测试父对象”,该子类具有子“测试子对象”. Test Child也是父母,并且有一个名为Test Sub Child的孩子,该孩子没有任何孩子.
需要输出示例:
array (
'Collections' =>
array (
'Sports' => NULL,
'Charity' => NULL,
),
'Test Parent' =>
array (
'Test Child' =>
array (
'Test Sub Child' => NULL,
),
),
'Test Parent 2 with No kids' => NULL,
'Study' =>
array (
'Study Groups' => NULL,
),
)
我尝试了一个解决方案,但无法正确获取语法,因此我可以创建一个带有孩子的孩子的附加数组.
我不一定需要重构我的示例.我只是在寻找最佳的解决方案.
我的示例代码
$category_structure = array();
foreach($event_categories as $main_cat => $content_ids) {
$this_category_list = explode('>', $main_cat);
$this_cat = array();
$this_parent = array_shift($this_category_list);
foreach($this_category_list as $cat) {
$this_cat[$this_parent][$cat] = null;
}
$category_structure = array_merge_recursive($this_cat, $category_structure);
}
解决方法:
这应该为您工作,确保结果中没有零索引项目.我认为这来自array_merge_recursive,通过将空值项合并到具有关联键的项.
虽然它不如P0rnflake的解决方案那么优雅,但是我相信您会明白的.
$collect = array();
$result = array();
$last = "";
foreach($event_categories as $main_cat => $content_ids) {
if (strpos($last, $main_cat) === false) {
array_push($collect, explode('>', $main_cat));
}
$last = $main_cat;
}
array_walk($collect, function($value) use (&$result) {
$out = array();
$cur = &$out;
foreach ($value as $array) {
if (count($value) !== 1) {
$cur[$array] = array();
} else {
$cur[$array] = null;
}
$cur = &$cur[$array];
}
$cur = null;
$result = array_merge_recursive($result, $out);
});
var_dump($result);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。