【问题标题】:How can i order this list using paired father-son with php?我如何使用配对的父子与 php 来订购此列表?
【发布时间】:2019-08-27 18:05:10
【问题描述】:

我正在编写一个选择框,其中包含来自分层 id-parent 数据库的数据。数据是这样的: id - parent_id

126 - 120
114 - 108
105 - 52
140 - 116
142 - 116
145 - 116
122 - 120
116 - 3
118 - 116
125 - 120
102 - 3
123 - 120
120 - 3
130 - 116
119 - 116
128 - 120
141 - 116
117 - 116
121 - 120
104 - 2

我需要这样组织:

array(
    3 => array(
        102 => array(
                    122, 123, 125
               )
        )
        116...
        120...
    )
)

到目前为止的代码

foreach($rsCat->linha() as $cat){ 
    append($cat, $list); 
} 
function append($cat, &$list){ 
    if( array_key_exists($cat->subcat, $list) ){ 
        $this->pendura($cat, $list[$cat->subcat]); 
    }
    else  { 
        $list[$cat->subcat][] = $cat->cat_id; 
    }   
}

【问题讨论】:

  • 到目前为止你有没有努力解决这个问题?
  • 我尝试过,但到目前为止..

标签: php arrays list tree


【解决方案1】:

你必须使用递归函数/方法:

function recursiveGroup($level, $grouped) {
    $result = [];
    foreach ($grouped[$level] as $item) {
        $result[$item] = recursiveGroup($item, $grouped);
    }

    return $result;
}

$array = [126 => 120, 114 => 108, ...];

$grouped = [];
foreach ($array as $child => $parent) {
    if (!array_key_exists($parent, $grouped)) {
        $grouped[$parent] = [];
    }

    $grouped[$parent][] = $child;
}

// Here we find minimal id for the beginning of our grouped array
$minId = min(array_keys($grouped));

$result[$minId] = recursiveGroup($minId, $grouped);

var_dump($result);

【讨论】:

    【解决方案2】:

    不使用递归,但这确实将项目重新排序...

    $input = [[126, 120],
        [114, 108],
        [105, 52],
        [140, 116],
        [142, 116],
        [145, 116],
        [122, 120],
        [116, 3],
        [118, 116],
        [125, 120],
        [102, 3],
        [123, 120],
        [120, 3],
        [130, 116],
        [119, 116],
        [128, 120],
        [141, 116],
        [117, 116],
        [121, 120],
        [104, 2]];
    
    // Sort the input
    rsort($input);
    $output = [];
    foreach ( $input as $pair ) {
        // pair[0] is the child ID, pair[1] is the parent ID
        // Check if existing item should be promoted to it's new parent ID
        if ( isset($output[$pair[0]]) ) {
            $output[$pair[1]][$pair[0]] = $output[$pair[0]];
            // Remove the old item
            unset($output[$pair[0]]);
        }
        else {
            // Add new child item to parent
            $output[$pair[1]][] = $pair[0];
        }
    }
    print_r($output);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-31
      • 1970-01-01
      • 1970-01-01
      • 2012-03-28
      • 1970-01-01
      • 2021-08-05
      • 2017-08-23
      • 1970-01-01
      相关资源
      最近更新 更多