Skip to content

Instantly share code, notes, and snippets.

@robsonke
Created June 14, 2014 08:17
Show Gist options
  • Save robsonke/b5df1a1b278ec1c5e8bf to your computer and use it in GitHub Desktop.
Save robsonke/b5df1a1b278ec1c5e8bf to your computer and use it in GitHub Desktop.
Group a php array to a tree structure
$original = array
(
"1" => array
(
"id" => 1,
"type" => "mtb",
"brand" => "scott",
"name" => "scott1"
),
array
(
"id" => 2,
"type" => "mtb",
"brand" => "cube",
"name" => "cube1"
),
array
(
"id" => 3,
"type" => "race",
"brand" => "cube",
"name" => "cuberace1"
),
array
(
"id" => 4,
"type" => "race",
"brand" => "giant",
"name" => "giant1"
),
array
(
"id" => 5,
"type" => "mtb",
"brand" => "cube",
"name" => "cube2"
)
);
echo "<pre>";
print_r($original);
echo "</pre>";
$converted = array();
$keys = array('type', 'brand');
$level = 0;
$converted = createTree($original, $keys);
echo "<pre>";
print_r($converted);
echo "</pre>";
function createTree($original, $keys, $level = 0)
{
$converted = array();
$key = $keys[$level];
$isDeepest = sizeof($keys) -1 == $level;
$level++;
$filtered = array();
foreach ($original as $k => $subArray)
{
$thisLevel = $subArray[$key];
if($isDeepest) $converted[$thisLevel][] = $subArray;
else $converted[$thisLevel] = array();
$filtered[$thisLevel][] = $subArray;
}
if(!$isDeepest)
{
foreach (array_keys($converted) as $value)
{
$converted[$value] = createTree($filtered[$value], $keys, $level);
}
}
return $converted;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment