Last active
October 27, 2016 19:30
-
-
Save iron-viper/5c03ffe3abf0198c9dd8378d31a372c0 to your computer and use it in GitHub Desktop.
Find ids in tree array by parent id includes parent id(recursively)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* @author iron-viper | |
*/ | |
$array = [ | |
[ | |
"id" => 1, | |
"name" => "test-1", | |
"parent" => 0, | |
"children" => [ | |
[ | |
"id" => 11, | |
"name" => "test-11", | |
"parent" => 1, | |
"children" => [ | |
[ | |
"id" => 111, | |
"name" => "test-111", | |
"parent" => 11, | |
], | |
[ | |
"id" => 112, | |
"name" => "test-112", | |
"parent" => 11, | |
] | |
] | |
] | |
] | |
], | |
[ | |
"id" => 2, | |
"name" => "test-2", | |
"parent" => 0 | |
], | |
[ | |
"id" => 3, | |
"name" => "test-3", | |
"parent" => 0, | |
"children" => [ | |
[ | |
"id" => 31, | |
"name" => "test-31", | |
"parent" => 3, | |
"children" => [ | |
[ | |
"id" => 311, | |
"name" => "test-111", | |
"parent" => 31, | |
"children" => [ | |
[ | |
"id" => 411, | |
"name" => "test-111", | |
"parent" => 311, | |
] | |
] | |
] | |
] | |
], | |
[ | |
"id" => 321, | |
"name" => "test-111", | |
"parent" => 3, | |
] | |
] | |
] | |
]; | |
function find($id, $array, &$res) | |
{ | |
foreach ($array as $row) { | |
if ($row["id"] == $id || $row["parent"] == $id) { | |
$res[] = $row["id"]; | |
if ($row["children"]) { | |
find($row["id"], $row["children"],$res); | |
} | |
} else { | |
if ($row["children"]) { | |
find($id, $row["children"],$res); | |
} | |
} | |
} | |
} | |
// example | |
find(31, $array, $res); | |
var_dump($res); | |
/* result | |
array(3) { | |
[0]=> | |
int(31) | |
[1]=> | |
int(311) | |
[2]=> | |
int(411) | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment