note 86010 modified in function.array-walk-recursive by thiago

From: Date: Mon, 29 Sep 2008 12:46:33 +0000
Subject: note 86010 modified in function.array-walk-recursive by thiago
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-144875@lists.php.net to get a copy of this message
If you will know that a tree in DB is not huge you can use array_walk_recursive to create tree structure e.g. in array. let's assume following table: NAME PARENT a null b null c null a1 a a2 a b1 b b11 b1 b111 b11 <?php require_once 'Zend/Db/Adapter/Pdo/Sqlite.php'; function treeFunc(&$item, $key, $dbConn) { $res = $dbConn->fetchPairs('SELECT name FROM tree where parent = ?',$key); if(!empty($res)) $item = $res; } $arr = $dbConn->fetchPairs('SELECT name FROM tree where parent is null'); // fetchPairs -> value is the index $valid = true; while($valid) { $oldCount = count($arr,COUNT_RECURSIVE); array_walk_recursive($arr, 'treeFunc',$dbConn); $newCount = count($arr,COUNT_RECURSIVE); if ($oldCount == $newCount) // if there is no change, exit... $valid = false; } print_r($arr); ?> -------------------------------------------------- Array ( [a] => Array ( [a1] => [a2] => ) [b] => Array ( [b1] => Array ( [b11] => Array ( [b111] => ) ) ) [c] => ) --was-- If you will know that a tree in DB is not huge you can use array_walk_recursive to create tree structure e.g. in array. let's assume following table: NAME PARENT a null b null c null a1 a a2 a b1 b b11 b1 b111 b11 <code> require_once 'Zend/Db/Adapter/Pdo/Sqlite.php'; function treeFunc(&$item, $key, $dbConn) { $res = $dbConn->fetchPairs('SELECT name FROM tree where parent = ?',$key); if(!empty($res)) $item = $res; } $arr = $dbConn->fetchPairs('SELECT name FROM tree where parent is null'); // fetchPairs -> value is the index $valid = true; while($valid) { $oldCount = count($arr,COUNT_RECURSIVE); array_walk_recursive($arr, 'treeFunc',$dbConn); $newCount = count($arr,COUNT_RECURSIVE); if ($oldCount == $newCount) // if there is no change, exit... $valid = false; } print_r($arr); </code> -------------------------------------------------- Array ( [a] => Array ( [a1] => [a2] => ) [b] => Array ( [b1] => Array ( [b11] => Array ( [b111] => ) ) ) [c] => ) http://php.net/manual/en/function.array-walk-recursive.php

« previous php.notes (#144875) next »