php数组表输出

时间:2013-12-18 15:19:46

标签: php arrays forms html-table

我几乎完成了这项工作,但我有以下内容:

    <table border="1" cellpadding="2">

            <thead>
            <tr>
            <th>Item Code</th>
            <th>Description </th>
            <th>Qty </th>
            <th>Price </th>
            <th>Total </th>
            </tr>
            </thead>

<?php
$i = 1; // Count to tell you want row we are looping through… not needed just to help $grandTotal = 0;

 if (!empty($_POST)) {

// Dump POST values in array to see what the values look like
// You don't need this.  It's just to see if we have more than one row in the posted
// data from the form.
echo print_r($_POST);
// Loop through each line on invoice and do something with it... i.e. Insert into database.
foreach($_POST['itemCode'] as $row => $item) {
    echo '<tbody>';
    echo'<tr>';
    echo '<td>' . $_POST['itemCode'] . "" . "</td>";
    echo '<td>' . $_POST['itemDesc'] . "" . "</td>";
    echo '<td>' . $_POST['itemQty'] . "" . "</td>";
    echo '<td>' . $_POST['itemPrice'] . "" . "</td>";
    echo '<td>' . $_POST['itemLineTotal'] . "" . "</td>";
    echo'<tr>';
    echo'</tbody>';
    }
    }
?>
    </table>
<?php
$grandTotal .= $_POST['itemLineTotal'];



echo 'Order Total: ' . $grandTotal;

?>

但是这会输出以下内容:

这是我的javascript:

            $(document).ready(function () {

                // We are overriding the autocomplete UI menu styles to create our own.
                // You can add information from the returned json array as needed
                // Just be sure that your array contains the correct value when returned
                // You'll want to modify the data/item-data.php file for the returned values

                $.ui.autocomplete.prototype._renderItem = function (ul, item) {
                    return $("<li></li>")
                        .data("item.autocomplete", item)

                        // This is the autocomplete list that is generated
                        .append("<a class='additionalInfo'>" + item.jItemCode + " - " + item.jItemDesc/* + " " +

                        // This is the hover box that is generated when you hover over an item in the list
                        "<span class='additionalInfoColor'>" +
                        "<div><h4>Item Information</h4></div>" +
                        "<div><strong>Item Ccsacsacsacsascaode:</strong> " + item.jItemCode + "</div>" +
                        "<div><strong>Qty on Hand:</strong> " + item.jQtyOnHand + "</div>" +
                        "<div><strong>Merchant:</strong> &#8364;" + item.jItemPrice + "</div>" +
                        "<div><strong>Wholesale:</strong> &#8364;" + item.jItemWholesale + "</div>" +
                        "<div><strong>Retail:</strong> &#8364;" + item.jItemRetail + "</div>" +
                        "</span> </a>"*/)

                        .appendTo(ul);
                };

                // We don't want the user to leave the page if they have started working with it so we set the
                // onbeforeload method
                $('#itemCode').focus(function () {
                    window.onbeforeunload = function () {
                        return "You haven't saved your data.  Are you sure you want to leave this page without saving first?";
                    };
                });

                // Update invoice total when item Qty or Price inputs have been updated
                $("#itemQty, #itemPrice").on('keyup', function () {
                    // Locate the row we are working with
                    var $itemRow = $(this).closest('tr');
                    // Update the price.
                    updatePrice($itemRow);
                });



                // Use the .autocomplete() method to compile the list based on input from user
                $('#itemCode').autocomplete({
                    source: 'services/fetch-item-data.php',
                    minLength: 1,
                    select:function (event, ui) {
                        var $itemrow = $(this).closest('tr');
                        // Populate the input fields from the returned values
                        $itemrow.find('#itemCode').val(ui.item.jItemCode);
                        $itemrow.find('#itemDesc').val(ui.item.jItemDesc);
                        $itemrow.find('#itemPrice').val(ui.item.jItemPrice);

                        // Give focus to the next input field to recieve input from user
                        $('#itemQty').focus();
                        return false;
                    }
                });

                /*
                 * Here's where we start adding rows to the invoice
                 */

                // Add row to list and allow user to use autocomplete to find items.
                $("#addRow").on('click', function () {

                    // Get the table object to use for adding a row at the end of the table
                    var $itemsTable = $('#itemsTable');

                    // Create an Array to for the table row. ** Just to make things a bit easier to read.
                    var rowTemp = [
                        '<tr class="item-row">',
                        '<td><i id="deleteRow" class="icon-remove"></i></td>',
                        '<td><input type="text" name="itemCode[]" class="input-medium" value="" id="itemCode" /> </td>',
                        '<td><input type="text" name="itemDesc[]" class="input-large" value="" id="itemDesc"  readonly="readonly" /></td>',
                        '<td><input type="text" name="itemQty[]" class="input-mini" value="" id="itemQty" /></td>',
                        '<td><div class="input-prepend input-append"><span class="add-on">&#8364;</span><input name="itemPrice[]" class=" input-small" id="itemPrice" type="text"></div></td>',
                        '<td><div class="input-prepend input-append"><span class="add-on">&#8364;</span><input name="itemLineTotal[]" class=" input-small" id="itemLineTotal" type="text" readonly="readonly"></div></td>',
                        '</tr>'
                    ].join('');

                    var $row = $(rowTemp);

                    // save reference to inputs within row
                    var $itemCode = $row.find('#itemCode');
                    var $itemDesc = $row.find('#itemDesc');
                    var $itemPrice = $row.find('#itemPrice');
                    var $itemQty = $row.find('#itemQty');

                    // If the last row itemCode is empty then don't let the user continue adding a row
                    if ($('#itemCode:last').val() != '') {

                        // Add row after the first row in table
                        $('.item-row:last', $itemsTable).after($row);
                        $($itemCode).focus();

                        // apply autocomplete method to newly created row
                        $row.find('#itemCode').autocomplete({
                            source:'services/fetch-item-data.php',
                            minLength:1,
                            select:function (event, ui) {
                                $itemCode.val(ui.item.jItemCode);
                                $itemDesc.val(ui.item.jItemDesc);
                                $itemPrice.val(ui.item.jItemPrice);
                                // Give focus to the next input field to receive input from user
                                $itemQty.focus();
                                return false;
                            }
                        });

                        // Remove row when clicked
                        $row.find("#deleteRow").on('click', function () {
                            // Remove this row we clicked on
                            $(this).parents('.item-row').remove();
                            // Show alert we removed the row
                            updateMessage('.alert', 'Item was removed!', 2000);
                            // Hide delete Icon if we only have one row in the list.
                            if ($(".item-row").length < 2) $("#deleteRow").hide();
                            // Update total
                            update_total();
                        });

                        // Update the invoice total on keyup when the user updates the item qty or price input
                        // ** Note: This is for the newly created row
                        $row.find("#itemQty, #itemPrice").on('keyup', function () {
                            // Locate the row we are working with
                            var $itemRow = $(this).closest('tr');
                            // Update the price.
                            updatePrice($itemRow);
                        });


                    } else {
                        $('.alert').fadeIn('slow').html('You need to complete the item inputs');
                    }

                    // End if last itemCode input is empty
                    return false;
                });

            }); // End DOM


            /* Description: Update price function
            *  @param: $itemRow - Row Object
            * */

             var updatePrice = function($itemRow){
                // Calculate the price of the row.  Remove and $ so the calculation doesn't break
                var price = $itemRow.find('#itemPrice').val().replace("$", "") * $itemRow.find('#itemQty').val();
                price = roundNumber(price, 2);
                isNaN(price) ? $itemRow.find('#itemLineTotal').val("N/A") : $itemRow.find('#itemLineTotal').val(price);
                update_total();
            };

            var update_total = function() {
                var total = 0;
                $('input#itemLineTotal').each(function (i) {
                    price = $(this).val().replace("$", "");
                    if (!isNaN(price)) total += Number(price);
                });

                total = roundNumber(total, 2);
                $('#invGrandTotal').html("<h4>&#8364;" + total + "</h4>");

            };


            // Update message
            var updateMessage = function(msgType, message, delay){
                $('#alert').fadeIn('slow').addClass(msgType).html(message).delay(delay).fadeOut('slow');
            };


            //########################################################################################################################

            // from http://www.mediacollege.com/internet/javascript/number/round.html
            function roundNumber(number, decimals) {
                var newString;// The new rounded number
                decimals = Number(decimals);
                if (decimals < 1) {
                    newString = (Math.round(number)).toString();
                } else {
                    var numString = number.toString();
                    if (numString.lastIndexOf(".") == -1) {// If there is no decimal point
                        numString += ".";// give it one at the end
                    }
                    var cutoff = numString.lastIndexOf(".") + decimals;// The point at which to truncate the number
                    var d1 = Number(numString.substring(cutoff, cutoff + 1));// The value of the last decimal place that we'll end up with
                    var d2 = Number(numString.substring(cutoff + 1, cutoff + 2));// The next decimal, after the last one we want
                    if (d2 >= 5) {// Do we need to round up at all? If not, the string will just be truncated
                        if (d1 == 9 && cutoff > 0) {// If the last digit is 9, find a new cutoff point
                            while (cutoff > 0 && (d1 == 9 || isNaN(d1))) {
                                if (d1 != ".") {
                                    cutoff -= 1;
                                    d1 = Number(numString.substring(cutoff, cutoff + 1));
                                } else {
                                    cutoff -= 1;
                                }
                            }
                        }
                        d1 += 1;
                    }
                    if (d1 == 10) {
                        numString = numString.substring(0, numString.lastIndexOf("."));
                        var roundedNum = Number(numString) + 1;
                        newString = roundedNum.toString() + '.';
                    } else {
                        newString = numString.substring(0, cutoff) + d1.toString();
                    }
                }
                if (newString.lastIndexOf(".") == -1) {// Do this again, to the new string
                    newString += ".";
                }
                var decs = (newString.substring(newString.lastIndexOf(".") + 1)).length;
                for (var i = 0; i < decimals - decs; i++) newString += "0";
                //var newNumber = Number(newString);// make it a number if you like
                return newString; // Output the result to the form field (change for your purposes)
            }

显然,它没有从表的数组中获取正确的信息,但是在顶部输出正确的值?请帮忙。

3 个答案:

答案 0 :(得分:3)

由于每个$ _POST项都是一个数组,因此循环并拉出各个元素:

echo '<tbody>';
for ($i = 0; $i < count($_POST['itemCode']); $i++) {
    echo '<tr>';
    echo '<td>' . htmlspecialchars($_POST['itemCode'][$i]) . "</td>";
    echo '<td>' . htmlspecialchars($_POST['itemDesc'][$i]) . "</td>";
    echo '<td>' . htmlspecialchars($_POST['itemQty'][$i]) . "</td>";
    echo '<td>' . htmlspecialchars($_POST['itemPrice'][$i]) . "</td>";
    echo '<td>' . htmlspecialchars($_POST['itemLineTotal'][$i]) . "</td>";
    echo '</tr>';
}
echo '</tbody>';

P.S。在回显用户数据时使用htmlspecialchars以防止XSS并防止文本中的任何<字符吃掉文档。

答案 1 :(得分:2)

您正在使用一组值,您已将其作为键值对进行迭代。这里$ row将是数组的关键,即数组的索引

所以试试这个

foreach($_POST['itemCode'] as $row => $item) {
    echo'<tr>';
     echo '<td>' . $_POST['itemCode'][$row] . "" . "</td>";
     echo '<td>' . $_POST['itemDesc'][$row] . "" . "</td>";
     echo '<td>' . $_POST['itemQty'][$row] . "" . "</td>";
     echo '<td>' . $_POST['itemPrice'][$row] . "" . "</td>";
     echo '<td>' . $_POST['itemLineTotal'][$row] . "" . "</td>";
    echo'<tr>';

}

您可以找到更多信息here

答案 2 :(得分:0)

我认为这正是你所追求的。大约一个小时前刚刚为我正在进行的项目做了这件事。

function hash2table($data, $show_row_numbers = true) {
    $return = false;
    if($data) {
        $keys = array_keys($data[0]);
        $keys = array_merge(array(""), $keys);
        $return = "<table>";
        $return .= "<thead>";
        $return .= "<tr>";
        foreach($keys as $key => $value) {
            $return .= "<th>{$value}</th>";
        }
        $return .= "<tr>";
        $return .= "</thead>";
        $return .= "<tbody>";
        foreach($data as $row_key => $row) {
            $return .= "<tr>";
            if($show_row_numbers) $return .= "<th>{$row_key}</th>";
            foreach($row as $key => $value) {
                $return .= "<td>{$value}</td>";
            }
            $return .= "</tr>";
        }
        $return .= "</tbody>";
        $return .= "</table>";
        return $return;
    }
}