donglilian0061 2014-09-23 11:31
浏览 30
已采纳

PHP - 基于键中的字符分离数组

I have a PHP array from a submitted form that looks like the following

$form_data = Array (
    [input_1_1] => Product Name
    [input_1_2] => $8.00
    [input_1_3] => 2
    [input_2_1] => Other Product Name
    [input_2_2] => $3.50
    [input_2_3] => 8
)

I am looking for the best way to parse this so I can build something markup like this:

<table>
    <tr>
        <td>Product Name</td>
        <td>$8.00</td>
        <td>2</td>
    </tr>
    <tr>
        <td>Other Product Name</td>
        <td>$3.50</td>
        <td>8</td>
    </tr>
</table>

What would be most kosher way to do this?

Should I split this array into smaller arrays based on the 1st number (and then loop them)? Alternatively should I just build the markup based on sets of three, like:

<table>
    <tr>
        <td><?php echo $form_data[1]; ?></td>
        <td><?php echo $form_data[2]; ?></td>
        <td><?php echo $form_data[3]; ?></td>
    </tr>
    <tr>
        <td><?php echo $form_data[4]; ?></td>
        <td><?php echo $form_data[5]; ?></td>
        <td><?php echo $form_data[6]; ?></td>
    </tr>
</table>

Any help/advice appreciated.

  • 写回答

6条回答 默认 最新

  • dongyuqi3808 2014-09-23 11:40
    关注
    $last_group = '';
    foreach ($form_data as $key => $value) {
        preg_match('/input_(\d+)/', $key, $match);
        if ($match[1] != $last_group) {
            if ($last_group) {
                echo "</tr>
    ";
            }
            echo "<tr>
    ";
            $last_group = $match[1];
        }
        echo "<td>$value</td>
    ";
    }
    if ($last_group) {
        echo "</tr>
    ";
    }
    

    It would be better to structure your form like this, though:

    <input type="text" name="name[]">
    <input type="text" name="price[]">
    <input type="text" name="quantity[]">
    

    Then the $_POST['name'], $_POST['price'] and $_POST['quantity'] will be arrays, and you can iterate over them:

    foreach ($_POST['name'] AS $i => $name) {
        $price = $_POST['price'][$i];
        $quantity = $_POST['quantity'][$i];
        // Output the table row
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥15 java报错:使用mybatis plus查询一个只返回一条数据的sql,却报错返回了1000多条
  • ¥15 Python报错怎么解决
  • ¥15 simulink如何调用DLL文件
  • ¥15 关于用pyqt6的项目开发该怎么把前段后端和业务层分离
  • ¥30 线性代数的问题,我真的忘了线代的知识了
  • ¥15 有谁能够把华为matebook e 高通骁龙850刷成安卓系统,或者安装安卓系统
  • ¥188 需要修改一个工具,懂得汇编的人来。
  • ¥15 livecharts wpf piechart 属性
  • ¥20 数学建模,尽量用matlab回答,论文格式
  • ¥15 昨天挂载了一下u盘,然后拔了