John Davidson

php - Build URL path while recursively searching a hierarchical array for an id

0 comments
Message:


I have a multidimensional array and I want to build an url providing only the id of the children.


array (
0 =>
array (
'id' => '1',
'p_pag' => '0',
'link' => 'Contact',
'children' =>
array (
0 =>
array (
'id' => '2',
'p_pag' => '1',
'link' => 'Contact-County',
'children' =>
array (
0 =>
array (
'id' => '3',
'p_pag' => '2',
'link' => 'Contact-Town-1',
'children' =>
array (
),
),
),
),
),
),
)

I expect a function where to specify the array above and the id as 3 in order to obtain an link like this /Contact/Contact-County/Contact-Town-1/


My attempt:


function getlink($array,$id)
{
$link='';
foreach($array as $aindex => $aval)
{
if($aval['id']==$id){$link.='/'.$aval['link'];}
elseif($aval['children']){...}
}
}


My Answer:
> array(
> 'id' => 1,
> 'name' => 'Home',
> 'children' => array(
> 0 => array(
> 'id' => 2,
> 'name' => 'About',
> 'children' => array(
> 0 => array(
> 'id' => 3,
> 'name' => 'Team',
> 'children' => array()
> )
> )
> ),
> 1 => array(
> 'id' => 4,
> 'name' => 'Services',
> 'children' => array()
> )
> )
> )

function buildUrlPath($array, $id, $path = '') {
foreach ($array as $item) {
if ($item['id'] == $id) {
$path .= '/' . $item['id'];
return $path;
}
if (!empty($item['children'])) {
$result = buildUrlPath($item['children'], $id, $path . '/' . $item['id']);
if ($result) {
return $result;
}
}
}
return false;
}

$id = 3;
$urlPath = buildUrlPath($array, $id);
echo $urlPath; // Output: /1/2/3

Rate this post

5 of 5 based on 6086 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us