逗号分隔列表(PHP)的多维子数组?

时间:2016-03-04 23:58:38

标签: php multidimensional-array

该函数适用于从多维数组创建格式化表并将其分配给变量。当有一个子数组时,它会很好地嵌套另一个表,但相反,我想显示一个以逗号分隔的列表(仅对子数组有条件)。

什么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>

1 个答案:

答案 0 :(得分:0)

这是一种生成表格的方法,只要数据被认为更适合,就会将值表示为逗号分隔。

具体而言,如果数据是非嵌套的顺序数组,则数据将表示为逗号分隔,因此没有命名键。

这是:

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

“标题”样本数据的输出:

enter image description here

上一个答案:

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 等函数来转义数据的某些字符(例如小于号和符号字符)。