php数组表输出 [英] php array table output

查看:60
本文介绍了php数组表输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我几乎完成了此操作,但是我有以下内容:

I nearly have this done but I have the following:

    <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:

This is my 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)
            }

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

Obviously it is not getting the correct information from the array for the table but is outputting the correct values at the top? Please help.

推荐答案

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

Since each $_POST item is an array, loop and pull out the individual elements:

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并防止文本中的任何<字符占用文档.

P.S. Use htmlspecialchars when echoing user data to prevent XSS and prevent any < characters in the text from eating the document.

这篇关于php数组表输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆