Skip to content

Instantly share code, notes, and snippets.

@jougene
Last active May 23, 2016 07:38
Show Gist options
  • Save jougene/1d7be85a2462538bfe09abcdd43b1ff0 to your computer and use it in GitHub Desktop.
Save jougene/1d7be85a2462538bfe09abcdd43b1ff0 to your computer and use it in GitHub Desktop.
<?php

$contacts = [
    [
        'id'        => 1,
        'name'      => 'OAO Vorkuta',
        'parent_id' => null
    ],
    [
        'id'        => 2,
        'name'      => 'OAO burum burum',
        'parent_id' => 1
    ],
    [
        'id'        => 3,
        'name'      => 'OAO',
        'parent_id' => 1
    ],
    [
        'id'        => 5,
        'name'      => 'Tatiana Navka',
        'parent_id' => 3
    ],
    [
        'id'        => 6,
        'name'      => 'Roman Kostomarov',
        'parent_id' => 3
    ],
    [
        'id'        => 4,
        'name'      => 'OAO',
        'parent_id' => 1
    ],
    [
        'id'        => 7,
        'name'      => 'OAO Severstal',
        'parent_id' => null
    ],

];

$arr_cat = [];
function getPidTree($array) {
    foreach ($array as $item) {
        if(empty($arr_cat[$item['parent_id']])) {
            $arr_cat[$item['parent_id']] = array();
        }
        $arr_cat[$item['parent_id']][] = $item;
    }
    return $arr_cat;
}

function showTree($arr, $parent_id = null) {

	if(empty($arr[$parent_id])) {
		return;
	}
	echo '<ul>';
	for($i = 0; $i < count($arr[$parent_id]); $i++) {
		echo "<li>{$arr[$parent_id][$i]['id']}
					{$arr[$parent_id][$i]['name']}";
		showTree($arr, $arr[$parent_id][$i]['id']);
		echo '</li>';
	}
	echo '</ul>';
}

$cnt = getPidTree($contacts);
showTree($cnt);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment