如何在PHP中显示此多维数组?

时间:2019-06-22 04:57:16

标签: php arrays multidimensional-array

我需要显示以下代码,以使汽车模型(日产,梅赛德斯,福特)为<form class="form-edit-add find_crime" role="form" method="POST" enctype="multipart/form-data"> <input type='text' class="form-control start_date" name ="start_date" id="start_date"/> <input type='text' class="form-control end_date" name ="end_date" id="end_date"/> </form> ,年份为$(function(){ $.validator.addMethod("greaterThan", function(value, element, params) { if (!/Invalid|NaN/.test(new Date(value))) { return new Date(value) > new Date($(params).val()); } return isNaN(value) && isNaN($(params).val()) || (Number(value) > Number($(params).val())); },'Must be greater than {0}.'); $("#end_date").rules('add', { greaterThan: "#start_date" }); $(".find_crime").validate({ rules: { EndDate: { greaterThan: "#start_date" } } }); }); ,子数组项为在<h1>中。我该怎么办?

<h3>

1 个答案:

答案 0 :(得分:3)

我们可能只想在string中定义一个foreach,然后在遍历数组时不断对其append进行定义:

$cars = array(
    array(
        "Nissan",
        2012,
        array(
            "power steering",
            "a/c",
        ),
    ),

    array(
        "Mercedes",
        2013,
        array(
            "power steering",
            "leather seats",
            "sunroof",
        ),
    ),

    array(
        "Ford",
        2010,
        array(
            "power steering",
            "a/c",
            "power windows",
            "window locks",
        ),
    ),
);

$html = '';
foreach ($cars as $key => $car) {
    $html .= '<h1>' . $car[0] . '</h1>';
    $html .= '<h3>' . $car[1] . '</h3>';
    $html .= '<ul>';
    foreach ($car[2] as $key => $attr) {
        $html .= '<li>' . $attr . '</li>';
    }
    $html .= '</ul>';
}

echo $html;

输出

<h1>Nissan</h1><h3>2012</h3><ul><li>power steering</li><li>a/c</li></ul><h1>Mercedes</h1><h3>2013</h3><ul><li>power steering</li><li>leather seats</li><li>sunroof</li></ul><h1>Ford</h1><h3>2010</h3><ul><li>power steering</li><li>a/c</li><li>power windows</li><li>window locks</li></ul>

建议

Vivek_23建议:

  

只是内爆li部分。

基于此,我们的代码可能看起来像这样简单:

$html = '';
foreach ($cars as $car) {
    $html .= '<h1>' . $car[0] . '</h1>';
    $html .= '<h3>' . $car[1] . '</h3>';
    $html .= '<ul><li>' . implode('</li><li>', $car[2]) . '</li></ul>';
}

echo $html;