hierarchy

<?php

function get_hierarchical_table_from_non_hierarchical_table( $t ) {
	
	/*
	
	$t = array(
		
		array( 'a', 'a', 'a' ),
		array( 'a', 'a', 'b' ),
		array( 'a', 'b', 'b' ),
		array( 'b', 'b', 'b' )
		
	);
	
	$r = get_hierarchical_table_from_non_hierarchical_table( $t );
	
	*/
	
	/* $r = array(
		
		array( 'a', 'a', 'a' ),
		array(  '',  '', 'b' ),
		array(  '', 'b', 'b' ),
		array( 'b', 'b', 'b' )
		
	);
	
	*/

	/*

	a   a   a
	a   a   b
	a   b   b
	b   b   b

	a   a   a
	b
	b   b
	b   b   b

	*/

	/*

	ALGO: high
	DATE: 2024-11-19 23:30
	TAGS: hierarchy

	*/

	for ( $j=0; $j<count( $t[0] ); $j++ ) { // each cell of line 0
	
		$r[0][$j] = $t[0][$j]; // result table

	} // for

	for ( $i=1; $i<count( $t ); $i++ ) { // each line from line 1 on
	
		for ( $j=0; $j<count( $t[$i] ); $j++ ) { // each cell

			$sw = 1; // switch on

			for ( $k=0; $k<=$j; $k++ ) { // each cell until/including cell $j

				if ( $t[$i][$k] != $t[$i-1][$k] ) $sw = 0; // compare with cell above; any mismatch puts switch off

			} // for

			if ( $sw == 0 ) $cr = $t[$i][$j]; // $cr =^= result table cell
			else $cr = ""; 

			$r[$i][$j] = $cr;

		} // for

	} // for

	return $r;

} // function

function get_non_hierarchical_table_from_hierarchical_table( $t ) {

	/*

	$t = array(

		array( 'a', 'a', 'a' ),
		array(  '',  '', 'b' ),
		array(  '', 'b', 'b' ),
		array( 'b', 'b', 'b' )

	);

	$r = get_non_hierarchical_table_from_hierarchical_table( $t );

	*/

	/* $r = array(

		array( 'a', 'a', 'a' ),
		array( 'a', 'a', 'b' ),
		array( 'a', 'b', 'b' ),
		array( 'b', 'b', 'b' )

	);

	*/

	/*

	a   a   a
	b
	b   b
	b   b   b

	a   a   a
	a   a   b
	a   b   b
	b   b   b

	*/

	/*
	
	ALGO: high
	DATE: 2024-11-19 23:45
	TAGS: hierarchy

	*/

	for ( $i=1; $i<count( $t ); $i++ ) { // each line, starting with line 1 (not 0)

		for ( $j=0; $j<count( $t[$i] ); $j++ ) { // each cell

			$ct = $t[$i][$j]; // this cell
			$cp = $t[$i-1][$j]; // prev. cell

			if ( $ct == "" ) $cr = $cp; // if cell is empty: take cell above // $cr =^= cell result
			else $cr = $ct; // else: take this cell

			$r[$i][$j] = $cr;

		} // for

	} // for

return $r;

} // function

?>