gpt4 book ai didi

php - 在 PHP 的树中转换具有逗号分隔值的字符串

转载 作者:行者123 更新时间:2023-11-29 20:56:24 25 4
gpt4 key购买 nike

我有一个 csv 文件,其中包含一个带有类别树的字段,采用逗号分隔格式,如下所示:

MotherCategory, ChildCategory1, ChildCategory2, ecc.

某些记录仅包含一个类别,其他记录包含两个类别,其他记录包含三个或更多类别。

我希望能够在我的数据库中存储所有唯一类别,并使用 parentid 方案组织每条记录,其中 parentid 值是 id上一级类别的

最后我应该有这样的东西:

id: 1, catname: MotherCategory, parentid: NULL
id: 2, catname: ChildCategory1, parentid: 1
id: 3, catname: ChildCategory2, parentid: 2

我已经使用 array_unique() 过滤了数据,删除了重复项,接下来使用 explode() 我能够分离这些值,并且对这些值进行计数根据结果​​数组的长度分隔组来构建一棵树,但我认为目前我缺少一些东西来获得最终结果。

我有以下代码。有人可以给我一个解决问题的提示吗?

$cats = array_of_comma_separated_values;

foreach ($cats as $cat) {
$catarray[] = explode(",",$cat);
}

//first level
$level1 = array_filter ($catarray, function($item) {
if (count($item) == 1) { return true; } return false;
});

//second level
$level2 = array_filter ($catarray, function($item) {
if (count($item) == 2) { return true; } return false;
});

$level3 = array_filter ($catarray, function($item) {
if (count($item) == 3) { return true; } return false;
});

$level4 = array_filter ($catarray, function($item) {
if (count($item) == 4) { return true; } return false;
});

$level5 = array_filter ($catarray, function($item) {
if (count($item) == 5) { return true; } return false;
});

$level6 = array_filter ($catarray, function($item) {
if (count($item) == 6) { return true; } return false;
});

$level7 = array_filter ($catarray, function($item) {
if (count($item) == 7) { return true; } return false;
});

这给了我几个数组,我必须迭代它们才能实现我正在寻找的东西。

现在,感谢 Kovlar 的建议,我正在开发基于 array_pop()array_replace_recurive() 的东西。

我编辑了这篇文章,因为也许我不太清楚。

最佳答案

我建议使用array_replace_recursive()来简化树合并:)

// $tree will contain the tree at the end of the script
$tree = [];
// we treat each row of the csv one by one
foreach($csv_rows as $row) {
// first, we split the string into an array
$root_to_leaf = explode(',', $row['root_to_leaf']);
// this is the "leaf" we want to append to the tree
$leaf = [array_pop($root_to_leaf) => $row['value']];
// we rebuild the path from the leaf to the root
while(!empty($root_to_leaf)) {
// add the next branching toward the root
$leaf = [array_pop($root_to_leaf) => $leaf];
}
// we append the leaf to the tree
$tree = array_replace_recursive($tree, $leaf);
}

关于php - 在 PHP 的树中转换具有逗号分隔值的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37596339/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com