<?php
function item_by_value($array,$key,$value) {
// returns FIRST matching element only, presumes ID
if ((!is_array($array)) || empty($key) || empty($value)) return false;
for ($i=0; $i < count($array); $i++) {
$item = (array) $array[$i];
if ($item[$key] == $value) {
return $array[$i];
break;
}
}
return null;
}
function article_link($article,$articles) {
if (is_null($article) || !is_object($article)) {return '';}
if ($article->parentPage == 'self') {
return '/'.$article->id;
}
else {
$parent = item_by_value($articles,'id',$article->parentPage);
return is_null($parent) ? '/'.$article->id : article_link($parent->id,$articles).'/'.$article->id;
}
}
$articles = json_decode('{"articles":[{"id":"about","title":"Significant Object","bodyHtml":"about-main.html","parentPage":"self","banner":"stock"},{"id":"workshops","title":"Workshops","bodyHtml":"workshops.html","parentPage":"self","banner":null},{"id":"making","title":"Making","bodyHtml":"making.html","parentPage":"self"},{"id":"the-lion-the-witch-and","title":"The Lion, The Witch and The Wardrobe","bodyHtml":"the-lion-the-witch.html","parentPage":"past"},{"id":"circus-1903","title":"Circus 1903","bodyHtml":"circus-1903.html","parentPage":"current","banner":"stock"},{"id":"dissonance","title":"Dissonance","bodyHtml":"dissonance.html","parentPage":"current"},{"id":"handspring-uk","title":"Handspring UK","bodyHtml":"handspring-uk.html","parentPage":"past","banner":"stock"},{"id":"james-ii","title":"James II","bodyHtml":"james-ii.html","parentPage":"past"},{"id":"die-bruder-lowenherz","title":"Die Brüder Löwenherz (The Brothers Lionheart)","bodyHtml":"lowenherz.html","parentPage":"past"},{"id":"newman","title":"Newman","bodyHtml":"newman.html","parentPage":"past"},{"id":"stiller","title":"Stiller","bodyHtml":"stiller.html","parentPage":"past"},{"id":"the-loris","title":"The Loris","bodyHtml":"the-loris.html","parentPage":"past"},{"id":"reviews-of-stiller","title":"Press Reviews of Stiller","bodyHtml":"reviews-of-stiller.html","parentPage":"stiller","banner":"none"},{"id":"jubilee-salute","title":"Jubilee Salute","bodyHtml":"jubilee-salute-handspring-UK.html","parentPage":"past"},{"id":"crow","title":"Crow","bodyHtml":"crow.html","parentPage":"past"}]}');
$test = $articles->articles[10];
$array = $articles->articles;
echo article_link($test,$array);
preferences:
56.88 ms | 402 KiB | 5 Q