将PHP数组切成表

时间:2015-03-21 05:08:25

标签: php arrays

不确定“slice”是否是正确的单词..但是我将以下数组存储在变量中。

Array (
[0] => Design|1-cylinder 4-stroke engine, water-cooled
[1] => Displacement|373.2 cm³
[2] => Bore|89 mm
[3] => Stroke|60 mm
[4] => Performance|32 kW (43 hp)
[5] => Starting aid|Electric starter
[6] => Transmission|6 speed, claw shifted
[7] => Engine lubrication|Wet sump
) 1 

注意分隔内容的“|”。这个内容应该在这样的表格中。

<table>
    <thead>
        <tr>
            <td>Title</td>
            <td>Details</td>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Engine Displacement</td>
            <td>373.2 cm³</td>
        </tr>
        <tr>
            <td>Transmission</td>
            <td>6 speed, claw shifted</td>
        </tr>
    </tbody>
</table>

我如何编写一个可以执行此操作的foreach语句?我甚至不知道从哪里开始?我应该分开阵列吗?不确定。

提前致谢!

1 个答案:

答案 0 :(得分:0)

$aData = array(
    'Design|1-cylinder 4-stroke engine, water-cooled',
    'Displacement|373.2 cm³',
    'Bore|89 mm',
    'Stroke|60 mm',
    'Performance|32 kW (43 hp)',
    'Starting aid|Electric starter',
    'Transmission|6 speed, claw shifted',
    'Engine lubrication|Wet sump'
);
?>
<table>
    <thead>
        <tr>
            <th>Title</th>
            <th>Details</th>
        </tr>
    </thead>
    <tbody>
    <?php
        $iCountData = count( $aData );
        for( $i = 0; $i < $iCountData; ++$i )
        {
            $aTmp = explode( '|', $aData[ $i ] );
            echo '<tr>';
            echo '<td>';
            echo $aTmp[ 0 ];
            echo '</td>';
            echo '<td>';
            echo $aTmp[ 1 ];
            echo '</td>';
            echo '</tr>';
        }
    ?>
    </tbody>
</table>