簡體   English   中英

多維子數組到逗號分隔列表(PHP)?

[英]Multi-Dimensional Sub-Array to Comma Separated List (PHP)?

該函數很好地用於從多維數組創建格式化表並將其分配給變量。 當有子數組時,它將很好地嵌套另一個表,但是,我想顯示一個逗號分隔的列表(僅對子數組有條件)。

哪些php函數/邏輯可以幫助我完成此操作,應如何實現?

當前顯示此...

<table>
<tr>
    <td><span style="color:#ffeeee;">Keywords</span></td>
    <td>
        <span style="color:#eeeeff;">

            <table>
            <tr>
                <td><span style="color:#ccffcc;">Alex</span></td>
            </tr>
            <tr>
                <td><span style="color:#ccffcc;">Mic</span></td>
            </tr>
            <tr>
                <td><span style="color:#ccffcc;">snowboarding</span></td>
            </tr>
            </table>

        </span>
    </td>
</tr>
</table>

會喜歡這樣的東西...

<table>
<tr>
    <td><span style="color:#ffeeee;">Keywords</span></td>
    <td><span style="color:#eeeeff;">Alex, Mic, snowboarding</span></td>
</tr>
</table>

PHP代碼(display_array_processor.php):

//----------------------------------------------------//
/*
// Iterating complex php multidimensional multi-level array 
// to html table using return instead of echo
*/
//----------------------------------------------------//

if($_POST)
{
    //check if its an ajax request, exit if not
    if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
        $output = json_encode(array( //create JSON data
            'type'=>'error', 
            'text' => 'Sorry Request must be Ajax POST'
        ));
        die($output); //exit script outputting json data
    } 

    $process_method     = $_POST["process_method"];
    $process_levels     = $_POST["process_levels"];

    //Sanitize input data using PHP filter_var()
    //$process_method       = filter_var($_POST["process_method"], FILTER_SANITIZE_STRING);



    //----------------------------------------------------//

    if ($process_levels == "noheaders") {

        // Sample array from shell command (No Headings)...
        $myArray = array(
            array(
                "Size" => "914 kB", 
                "Date" => "2015:02:08 18:01:00-08:00", 
                "Attributes" => "Regular; (none)", 
                "Names" => 
                array(
                    "Alex Smith", 
                    "Mike Jones"
                ), 
                "Keywords" => 
                array(
                    2015, 
                    "Alex", 
                    "Mike", 
                    "snowboarding",
                    array(
                        'A snow',
                        'B cold',
                        'C fun'
                    )
                ), 
                "Software" => "Invisible Space-Monkey Monitoring System 01", 
                "Duration" => 4800
            )
        );

    } elseif ($process_levels == "headers") {

        // Sample array from shell command (With Headings)...
        $myArray = array(
            array(
                "SourceFile" => "test.txt",
                "Tool" =>
                array(
                    "Version" => 11.12
                ),
                "File" => 
                array(
                    "Size" => "104 kB",
                    "ModifyDate" => "2016:02:08 18:01:00-08:00"
                ),
                "Region" => 
                array(
                    "RegionAppliedToDimensionsUnit" => "pixel",
                    "RegionName" => 
                    array(
                        "Alex Smith",
                        "Mike Jones"
                    ),
                    "Subject" => 
                    array(
                        2015,
                        "Alex",
                        "Mike",
                        "snowboarding"
                    )
                )
            )
        );

    } else {

        // Small Sample Array...
        $myArray = array(
            "Source" => "test.txt"
        );

    }

    if ($process_method == "tables") {
        //$html = recursive_array($myArray);
        $html = recursive_array_table($myArray);
    } elseif ($process_method == "commas") {
        $html = array_table($myArray);
    } else {
        $html = "Do not know the process method.";
    }

    //$html .= '<p><textarea rows="10" cols="75">'.$process_method.'</textarea></p>';
    $output = json_encode(array('type'=>'message', 'text' => $html));
    die($output);
}


//----------------------------------------------------//
// Recursive Array Functions - COMMA SUB-ARRAYS
//----------------------------------------------------//

// Two generic utility functions:
function is_nested($array) {
    return is_array($array) && count($array) < count($array, COUNT_RECURSIVE);
}

function is_assoc($array) {
    return is_array($array) && array_keys($array) !== range(0, count($array) - 1);
}

function array_table_row($key, $row) {
    $content = array_table($row);
    return "<tr>\n<th>$key</th>\n<td>$content</td>\n</tr>\n";
}

function array_table($array) {
    if (is_nested($array) || is_assoc($array)) {
        $content = implode("", array_map('array_table_row', array_keys($array), $array));
        return "<table border=1>\n<tbody>\n$content</tbody>\n</table>\n";
    }
    // At this point $array is too simple for a table format:
    $color = is_array($array) ? "922" : "292";
    $content = htmlspecialchars(is_array($array) ? implode(", ", $array) : $array);
    return "<span style='color:#$color'>$content</span>";
}


//----------------------------------------------------//
// Recursive Array Functions - TABLE SUB-ARRAYS (ORIG)
//----------------------------------------------------//

function recursive_array_table($array) {
    return "<table border=1>\n<tbody>\n" . 
        recursive_array_table_row($array) .
        //implode("", array_map('recursive_array_table_row', array_keys($array), $array)) .
        "</tbody>\n</table>\n";
}
function recursive_array_table_row($array) {
    foreach($array as $key => $value) {
        $content .= '<tr>';
        if (is_array($value)) {
            $content .= '<td colspan="1"><span style="color:#992222;">'.htmlspecialchars($key).'</span></td>';
            $content .= '<td><span style="color:222299;">'.recursive_array_table($value).'</span></td>';
        } else {
            // Filter out some info...
            //if (
            //($key != "Error") && 
            //($key != "SourceFile")
            //) {
                //if (!is_numeric($key)) {
                    $content .= '<td>'.htmlspecialchars($key).'</td>';
                //}
                $content .= '<td><span style="color:#229922;">'.$value.'</span></td>';
            //}
        }
        $content .= '</tr>';
    }
    return $content;
}
function recursive_array_csv($array) {
    //return is_array($array) 
    //    ? "[" . implode(", ", array_map('array_csv', $array)) . "]"
    //    : htmlspecialchars($array);
}

HTML:

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function() {
    jQuery("#submit_btn").click(function() { 
        post_data = {
            'process_levels'    : jQuery('select[name=process_levels]').val(),
            'process_method'    : jQuery('select[name=process_method]').val(),
            'process_name'      : jQuery('input[name=process_name]').val(), 
            'process_msg'       : jQuery('textarea[name=process_message]').val()
        };
        jQuery.post('display_array_processor.php', post_data, function(response){  
            if(response.type == 'error'){ //load json data from server and output message     
                output = '<div class="error">'+response.text+'</div>';
            }else{
                output = '<div class="success">Done! Here is the response:</div><div>'+response.text+'</div>';
            }
            jQuery("#contact_results").hide().html(output).slideDown();
        }, 'json');
    });
});
</script>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="form-style" id="contact_form" style="max-width:650px;">
    <div id="contact_results"></div>
    <br />
    <div id="contact_body">
        <h3>Simple Bootstrap jQuery Ajax Form</h3>
        Levels:
        <select name="process_levels" id="process_levels" class="input-sm form-control" />
            <option value="noheaders">No Headers</option>
            <option value="headers">With Headers</option>
            <option value="">None</option>
        </select>
        Method:
        <select name="process_method" id="process_method" class="input-sm form-control" />
            <option value="commas">Commas</option>
            <option value="tables">Tables</option>
            <option value="">None</option>
        </select>
        <input type="submit" id="submit_btn" value="Submit" />
    </div>
</div>
</body>
</html>

這是一種生成表的方法,一旦認為該數據更適合,表中的值將以逗號分隔。

具體來說,如果數據是非嵌套的順序數組,那么數據將以逗號分隔表示,因此沒有命名鍵。

這里是:

// Two generic utility functions:
function is_nested($array) {
    return is_array($array) && count($array) < count($array, COUNT_RECURSIVE);
}

function is_assoc($array) {
    return is_array($array) && array_keys($array) !== range(0, count($array) - 1);
}

function array_table_row($key, $row) {
    $content = array_table($row);
    return "<tr>\n<th>$key</th>\n<td>$content</td>\n</tr>\n";
}

function array_table($array) {
    if (is_nested($array) || is_assoc($array)) {
        $content = implode("", array_map('array_table_row', array_keys($array), $array));
        return "<table border=1>\n<tbody>\n$content</tbody>\n</table>\n";
    }
    // At this point $array is too simple for a table format:
    $color = is_array($array) ? "922" : "292";
    $content = htmlspecialchars(is_array($array) ? implode(", ", $array) : $array);
    return "<span style='color:#$color'>$content</span>";
}

參見eval.in

“標題”樣本數據的輸出:

在此處輸入圖片說明

先前的答案:

function array_csv($array) {
    return is_array($array) 
        ? "[" . implode(", ", array_map('array_csv', $array)) . "]"
        : htmlspecialchars($array);
}

function array_table_row($index, $row) {
    return "<tr>\n  <th colspan='2'>Row ". ($index+1) . "</th>\n</tr>\n" .
        implode("", array_map(function ($key, $value) {
            return "<tr>\n  <td>" . htmlspecialchars($key) . "</td>\n" .
               "  <td><span style='color:#" . (is_array($value) ? "ccf" : "cfc") . ";'>" . 
                array_csv($value) . "</span></td>\n</tr>\n";
        }, array_keys($row), $row));
}

function array_table($array) {
    return "<table border=1>\n<tbody>\n" . 
        implode("", array_map('array_table_row', array_keys($array), $array)) .
        "</tbody>\n</table>\n";
}

echo array_table($myArray);

看到它在eval.in上運行。

這是樣本數據的輸出:

<table border=1>
<tbody>
<tr>
  <th colspan='2'>Row 1</th>
</tr>
<tr>
  <td>Size</td>
  <td><span style='color:#cfc;'>914 kB</span></td>
</tr>
<tr>
  <td>Date</td>
  <td><span style='color:#cfc;'>2015:02:08 18:01:00-08:00</span></td>
</tr>
<tr>
  <td>Attributes</td>
  <td><span style='color:#cfc;'>Regular; (none)</span></td>
</tr>
<tr>
  <td>Names</td>
  <td><span style='color:#ccf;'>[Alex Smith, Mike Jones]</span></td>
</tr>
<tr>
  <td>Keywords</td>
  <td><span style='color:#ccf;'>[2015, Alex, Mike, snowboarding, [A snow, B cold, C fun]]</span></td>
</tr>
<tr>
  <td>Software</td>
  <td><span style='color:#cfc;'>Invisible Space-Monkey Monitoring System 01</span></td>
</tr>
<tr>
  <td>Duration</td>
  <td><span style='color:#cfc;'>4800</span></td>
</tr>
</tbody>
</table>

從您的問題中尚不清楚,當數組嵌套得更深,超出了逗號分隔值的級別時,您要做什么。

使用上面的代碼,逗號分隔的列表被括在方括號中,因此很清楚子數組在此類列表中的開始和結束位置。

請注意,您應該使用htmlspecialchars之類的函數來轉義數據中的某些字符(例如小於號和&字符)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM