다차원 하위 배열에서 쉼표로 구분 된 목록 (PHP)으로?

잭 M.

이 함수는 다차원 배열에서 형식이 지정된 테이블을 만들고 변수에 할당하는 데 적합합니다. 하위 배열이 있으면 다른 테이블을 멋지게 중첩하지만 대신 쉼표로 구분 된 목록을 표시하고 싶습니다 (하위 배열에 대해서만 조건부).

이 작업을 수행하는 데 어떤 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>
Tricot

다음은 데이터가 더 적합한 것으로 간주되는 즉시 값이 쉼표로 구분되는 테이블을 생성하는 방법입니다.

구체적으로 데이터는 중첩되지 않은 순차적 배열 인 경우 쉼표로 구분되어 표시되므로 명명 된 키가 없습니다.

여기있어:

// 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] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

PHP는 쉼표로 구분 된 목록에서 배열을 만듭니다.

쉼표로 구분 된 값을 사용하여 다차원 배열의 항목 수 가져 오기-PHP

다른 쉼표로 구분된 목록에서 y에서 시작하는 x 항목의 쉼표로 구분된 목록을 얻는 방법

쉼표로 구분 된 목록을 사용하여 열에서 쉼표로 구분 된 값 찾기

배열에서 쉼표로 구분 된 목록 가져 오기

쉼표로 구분 된 인수 목록에서 쉼표로 구분 된 값을 구문 분석합니다.

mysql에서 쉼표로 구분 된 목록 교차

다차원 배열에서 쉼표로 구분 된 문자열 만들기

다차원 배열에서 쉼표로 구분 된 문자열 만들기

목록에 쉼표로 구분 된 값

쉼표로 구분 된 문자열의 다차원 배열

쉼표로 구분 된 목록의 하위 문자열에 대한 정규식

SQL의 하위 쿼리에서 쉼표로 구분 된 목록 만들기

열 값을 쉼표로 구분 된 값 목록으로 분할

쉼표로 구분 된 목록에서 값을 구분하고 쌓기

목록에서 쉼표로 구분 된 요소를 계산하고 다른 열에 저장

쉼표로 구분 된 값을 사용하여 다른 목록에서 목록 생성

열의 쉼표로 구분 된 목록에서 항목 제거

배열에서 쉼표로 구분 된 문자열 목록을 사용하여 MongoDB 집계 검색

PHP / MySQL 쿼리에서 쉼표로 구분 된 목록이 필요합니다.

perl에서 공백 또는 쉼표로 구분된 문자열을 목록으로 분할하려면

다른 열의 쉼표로 구분 된 목록 내에서 일치하는 ID를 기반으로 ID 목록 연결

쉼표를 종료하지 않고 C #의 목록에서 쉼표로 구분 된 목록 만들기

배열을 반복하고 쉼표로 구분 된 문자열에 내용을 추가하지만 최신 항목에서는 쉼표를 건너 뜁니다.

중첩 배열을 결합하고 쉼표로 구분된 목록을 출력합니다.

쉼표로 구분 된 목록에서 분할 된 값 삽입

쉼표로 구분 된 문자열을 목록으로 변환

쉼표로 구분 된 문자열을 목록으로 변환

열거 형을 쉼표로 구분 된 목록으로 저장

TOP 리스트

  1. 1

    JNDI를 사용하여 Spring Boot에서 다중 데이터 소스 구성

  2. 2

    std :: regex의 일관성없는 동작

  3. 3

    JSoup javax.net.ssl.SSLHandshakeException : <url>과 일치하는 주체 대체 DNS 이름이 없습니다.

  4. 4

    PrematureCloseException : 연결이 너무 일찍 닫혔습니다.

  5. 5

    Xcode10 유효성 검사 : 이미지에 투명성이 없지만 여전히 수락되지 않습니까?

  6. 6

    정점 셰이더에서 카메라에서 개체까지의 XY 거리

  7. 7

    Ionic 2 로더가 적시에 표시되지 않음

  8. 8

    Seaborn에서 축 제목 숨기기

  9. 9

    C #에서 'System.DBNull'형식의 개체를 'System.String'형식으로 캐스팅 할 수 없습니다.

  10. 10

    복사 / 붙여 넣기 비활성화

  11. 11

    ArrayBufferLike의 typescript 정의의 깊은 의미

  12. 12

    Google Play Console에서 '예기치 않은 오류가 발생했습니다. 나중에 다시 시도해주세요. (7100000)'오류를 수정하는 방법은 무엇입니까?

  13. 13

    Kubernetes Horizontal Pod Autoscaler (HPA) 테스트

  14. 14

    jfreecharts에서 x 및 y 축 선을 조정하는 방법

  15. 15

    PRNG 기간보다 순열이 더 많은 목록을 무작위로 섞는 방법은 무엇입니까?

  16. 16

    C # HttpWebRequest 기본 연결이 닫혔습니다. 전송시 예기치 않은 오류가 발생했습니다.

  17. 17

    다음 컨트롤이 추가되었지만 사용할 수 없습니다.

  18. 18

    잘못된 구성 개체입니다. Webpack이 Angular의 API 스키마와 일치하지 않는 구성 개체를 사용하여 초기화되었습니다.

  19. 19

    Android Kotlin은 다른 활동에서 함수를 호출합니다.

  20. 20

    R의 마침표와 숫자 사이에 문자열 삽입

  21. 21

    Assets의 BitmapFactory.decodeStream이 Android 7에서 null을 반환합니다.

뜨겁다태그

보관