Sorting an array into a multidimensional array based on “parent_id”

前端 未结 1 1243
北恋
北恋 2021-01-22 04:35

I\'m storing an infinitely nested directory structure in mysql by assigning a \"parent_album_id\" to each \"album\" (unless it\'s at the top level, in which case it does not hav

1条回答
  •  礼貌的吻别
    2021-01-22 05:02

    // you already managed to get the array into this form
    $albums = array(
      1 => array('id'=>1, 'title'=>'Album 1', 'parentId'=>null),
      2 => array('id'=>2, 'title'=>'Album 2', 'parentId'=>null),
      3 => array('id'=>3, 'title'=>'Album 1.1', 'parentId'=>1),
      4 => array('id'=>4, 'title'=>'Album 1.1.1', 'parentId'=>3),
      5 => array('id'=>5, 'title'=>'Album 2.1', 'parentId'=>2),
      6 => array('id'=>6, 'title'=>'Album 1.1.2', 'parentId'=>3),
      7 => array('id'=>7, 'title'=>'Album 1.1.3', 'parentId'=>3)
    );
    
    print_r(foo($albums));
    
    
    function foo($albums) {
      $rv = array();
      foreach( $albums as &$album) {
        if ( is_null($album['parentId']) ) {
          // no parentId -> entry in the root array
          $rv[] = &$album;
        }
        else {
          $pid = $album['parentId'];
          if ( !isset($albums[$pid]) ) {
            echo 'orphant album: ', $album['id'], "\n";
          }
          else {
            if ( !isset($albums[$pid]['children']) ) {
              $albums[$pid]['children'] = array();
            }
            $albums[$pid]['children'][] = &$album;
          }
        }
      }
      return $rv;
    }
    

    prints

    Array
    (
      [0] => Array
        (
        [id] => 1
        [title] => Album 1
        [parentId] => 
        [children] => Array
          (
            [0] => Array
            (
              [id] => 3
              [title] => Album 1.1
              [parentId] => 1
              [children] => Array
                (
                [0] => Array
                  (
                    [id] => 4
                    [title] => Album 1.1.1
                    [parentId] => 3
                  )
    
                [1] => Array
                  (
                    [id] => 6
                    [title] => Album 1.1.2
                    [parentId] => 3
                  )
    
                [2] => Array
                  (
                    [id] => 7
                    [title] => Album 1.1.3
                    [parentId] => 3
                  )
    
                )
    
            )
    
          )
    
        )
    
      [1] => Array
        (
        [id] => 2
        [title] => Album 2
        [parentId] => 
        [children] => Array
          (
            [0] => Array
            (
              [id] => 5
              [title] => Album 2.1
              [parentId] => 2
            )
    
          )
    
        )
    
    )
    

    0 讨论(0)
提交回复
热议问题