이 함수는 다차원 배열에서 형식이 지정된 테이블을 만들고 변수에 할당하는 데 적합합니다. 하위 배열이 있으면 다른 테이블을 멋지게 중첩하지만 대신 쉼표로 구분 된 목록을 표시하고 싶습니다 (하위 배열에 대해서만 조건부).
이 작업을 수행하는 데 어떤 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 와 같은 함수를 사용하여 데이터의 일부 문자 (예 :보다 작음 및 앰퍼샌드 문자)를 이스케이프해야합니다 .
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다