Skip to content

Instantly share code, notes, and snippets.

@karibot
Last active April 12, 2019 19:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save karibot/5a313d13b421d4f3a43bf2c0577498e6 to your computer and use it in GitHub Desktop.
Save karibot/5a313d13b421d4f3a43bf2c0577498e6 to your computer and use it in GitHub Desktop.
<?php
$rows=[
"/page1.html",
"/cocktails/receipe/page1.html",
"/cocktails/receipe/page2.html",
"/cocktails/page3.html",
"/article/magazine",
"/article/mood/page1.html"];
$res = [];
$i=0;
foreach($rows as $row){
$suffix = preg_replace("#https?://[^/]*#", "", $row);
$parts = array_values(array_filter(preg_split("#[/\?]#", $suffix)));
$res = create($parts, $res);
}
$data=['name' => '/','children' =>$res];
var_dump($data);
$json = json_encode($data);
function create($path, $res){
#print(path[0],dictionary)
if (empty($path))
return;
foreach($res as $ele){
if (array_key_exists("name", $ele) && $ele['name'] == $path[0]){
if (!array_key_exists("children", $ele)){
$ele['children'] = [];
}
if (count($path) > 1){
create(array_slice($path, 1), $ele['children']);
}
return;
}
}
$newvalue = ["name" => $path[0]];
if (count($path)>1){
$newvalue['children'] = [];
}
$res[] = $newvalue;
if (count($path)> 1){
create(array_slice($path, 1), end($res)['children']);
}
return $res;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment