Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- $langs = [
- [1,"Frontend", 0],
- [2,"Backend", 0],
- [3,"Angular", 1],
- [4,"Angular 1", 3],
- [5,"Vue", 1],
- [6,"React", 1],
- [7,"PHP", 2],
- [8,"Laravel", 7],
- [9,"Angular 1.8", 4]
- ];
- //Recursive generating childs function
- function generateAllChilds($id, $ar, $n){
- $childs = [];
- for($i = 0; $i < $n; $i++){
- if($id == $ar[$i][2]){
- array_push($childs, (object)[
- "id" => $ar[$i][0],
- "name" => $ar[$i][1],
- "childs" => generateAllChilds($ar[$i][0], $ar , $n)
- ]);
- }
- }
- return $childs;
- }
- function langsToArray($langArray){
- $ret = [];
- $len = count($langArray);
- //Getting root parents
- for($i = 0; $i < $len; $i++){
- if($langArray[$i][2] == 0){
- array_push($ret, (object)[
- "id" => $langArray[$i][0],
- "name" => $langArray[$i][1],
- "childs" => generateAllChilds($langArray[$i][0],$langArray, $len)
- ]);
- }
- }
- return $ret;
- }
- echo "<pre>";
- print_r(langsToArray($langs));
- echo "<pre>";
- echo $json = json_encode(langsToArray($langs));
- echo "<script>console.log('".$json."');</script>";
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement