Saturday 24 August 2013

Multidimensional Array structure to PHP HTML output?

Multidimensional Array structure to PHP HTML output?

I have repeated sections in my web site.
I'm trying to decrease them,
My approach is one time i will create a html schema (predefined as array),
via this schema my function undestranding that what kind of output user
needs and outputs results according to my variables..
My problem is I could not find a way to complete situation..
Input variables might be (infinitive)
$vals = array('Country Name' => 'USA', 'Country Name' => 'Canada',
'Country Name' => 'Mexico');
$vals = array('Country Name' => 'USA', 'Country Name' => 'Canada');
$vals = array('Country Name' => 'USA');
Expected outputs are in order
<div class="lines">
<div><span>Country Name</span>USA</div>
<div><span>Country Name</span>Canada</div>
<div><span>Country Name</span>Mexico</div>
</div>
<div class="lines">
<div><span>Country Name</span>USA</div>
<div><span>Country Name</span>Canada</div>
</div>
<div class="lines">
<div><span>Country Name</span>USA</div>
</div>
Schema is the variables that is totally suitable with html
$schema = array(
array(
'tag' => 'div',
'class' => 'lines',
array(
'tag' => 'div',
array(
'tag' => 'span',
'key' => '$key'
),
'key' => '$key'
),
)
);
My function creates outputs from this schema. (Schema might be expand
accordings to user need.)
function get_output($schema, $vals, $t = -1){
$t++;
$tag = "";
$atts = array();
$keys = array();
$code = array();
foreach($schema as $k => $v){
if(is_array($v)){
$keys[] = get_output($v, $vals, $t);
} else {
switch($k){
case "tag": $tag = $v; break;
case "key": break;
case "type": break;
default: $atts[$k] = $v; break;
}
}
}
//echo $t;
//$code[] = str_repeat("\t", $t);
if($tag){
$code[] = "<$tag"; foreach($atts as $k=>$v){ $code[] = '
'.$k.'="'.urlencode($v).'"'; } $code[] = ">";
$code = array(implode('', $code));
}
foreach($keys as $k){ $code[] = $k; }
if($tag){
//$code[] = "\n".str_repeat("\t", $t);
$code[] = '</'.$tag.'>';
}
//print_r($code);
return implode("", $code);
}
After all this process I will just call my function with the variables.,
Schema predefined once.
$vals = array('Country Name' => 'USA', 'Country Name' => 'Canada',
'Country Name' => 'Mexico');
echo get_output($schema, $vals, -1);

No comments:

Post a Comment