I
I
iamsaint2011-11-18 16:45:24
PHP
iamsaint, 2011-11-18 16:45:24

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(...),
  ...
)



On the page:

image

Answer the question

In order to leave comments, you need to log in

6 answer(s)
G
Gibbzy, 2011-11-18
@gibbzy

This is an elementary recursive function.
Do you write or can you do it yourself?

S
sajgak, 2011-11-18
@sajgak

The easiest option is nested [table] [/table] and recursion

R
Roman Skvazh, 2011-11-18
@rbatoon89

First you have to walk through the array and find the deepest level. This will come in handy for rowspan.

P
powder96, 2011-11-19
@powder96

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;
}

A
Anatoly, 2011-11-18
@taliban

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>

A normal layout designer will do anything from this style =)

A
Andrey, 2011-11-19
@RedOctoberCZ

Take a look here - it might be useful.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question