Answer the question
In order to leave comments, you need to log in
PHP → Output array to table
Good afternoon.
Can you please advise how in php you can display an array with an arbitrary nesting level in an html table?
Example:
in code:
array(
[bmw] => array (
[x3] => array(
[0] => 'black',
[1] => 'white'
[other] => array (...)
...
),
[x5] => array( ... ),
...
),
[audi] => array(...),
...
)
Answer the question
In order to leave comments, you need to log in
This is an elementary recursive function.
Do you write or can you do it yourself?
First you have to walk through the array and find the deepest level. This will come in handy for rowspan.
I wrote two functions that may be useful to you: one for calculating the table width (array depth) - so that you can correctly chop the table into rows, and the second for calculating the height of an arbitrary cell - so that you can set the rowspan. All functions are recursive.
// красивооформленный массив см. в моем дополнении к вопросу
$input = array('bmw'=>array('x3'=>array('black','white','...'=>array('...'),'other'=>
array('something','something')),'x5'=>array('black','white','...'=>array('...'))),'audi'=>
array('...'=>array('...'=>array('...'))));
echo' Table dimensions: ' . arrayVizualize_tableWidth($input) . ' x ' . arrayVizualize_tableHeight($input);
echo '<br />';
echo '<b>bmw</b> rowspan is: ' . arrayVizualize_tableHeight($input['bmw']);
function arrayVizualize_tableWidth($array, $currDepth = 1) {
$maximalDepth = $currDepth;
foreach($array as $element)
if(is_array($element)) {
$elementDepth = arrayVizualize_tableWidth($element, $currDepth + 1);
if($elementDepth > $maximalDepth)
$maximalDepth = $elementDepth;
}
return $maximalDepth;
}
function arrayVizualize_tableHeight($array) {
if(!is_array($array))
return 1;
$height = 0;
foreach($array as $element) {
if(is_array($element))
$height += arrayVizualize_tableHeight($element);
else
++$height;
}
return $height;
}
Do you need a sign?
<div> <div class="title">bmw</div> <div class="children"> <div> <div class="title">x5</div> <div class="children">...</div> </div> </div> </div>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question