weixin_33704234 2019-11-27 17:47 采纳率: 0%
浏览 82

格式解析的json数组

I have a project where I have an encoded json array and need to format it so the elements inside the array print underneath each other like so in the index.php file.

this is my desired output for the elements inside the array, to be printed out underneath each other with a space for each new index

Desired output

here is my code so far:

allNames.php

<?php
// Get the string from the URL
$json = file_get_contents('http://5dd559d3ce4c300014402cb8.mockapi.io/onboard/posts');
printAll($json);
$array= array();
function printAll($json){
// Decode the JSON string into an object
$obj = json_decode($json,true);
$elementCount  = count($obj);
// In the case of this input, do key and array lookups to get the values
for($i=0; $i<$elementCount; $i++){

    #delimit based on added * after each attribute to ensure all elemets are added and not cut short
    $array[]=explode("*",$obj[$i]["id"]."*".$obj[$i]["createdAt"]."*".$obj[$i]["name"]
            ."*".$obj[$i]["avatar"]."*".$obj[$i]["jobDescription"]."*".$obj[$i]["userEmail"]."*"
            .$obj[$i]["userIpAddress"]."*".$obj[$i]["userAgent"]);
}

 echo json_encode($array);
}
?>

index.php

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">

function ajax_post(){
     $.post("allNames.php", {
    }, function(data) {
      var returnedData = JSON.parse(data);
      $("#data").html(returnedData + "<br>");
    });
    };
</script>
</head>
<body>
<h2>Ajax Post to PHP and Get Return Data</h2>
<input name="myBtn" type="submit" value="Check" onclick="ajax_post()"> <br><br>
<center> <p id="data" style="color:black"></p><br><br> </center>
</body>
</html>
  • 写回答

1条回答 默认 最新

  • weixin_33674437 2019-11-27 19:14
    关注

    This formats the JSON for printing. It is a working example.

    The $dataToPrint variable holds everything you want to print from the data. It checks for empty data, also does not print a separator if no data was outputted. It is pretty straight forward, it loops through everything.

    If you dont want to limit what is printed, just remove the $dataToPrint variable and the array_search(... condition and just print it instead.

    index:

    <html>
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
        <script type="text/javascript">
    
            function ajax_post(){
                $.post("allNames.php", {
                }, function(data) {
                    // var returnedData = JSON.parse(data);
                    $("#data").html(data);
                });
            };
        </script>
    </head>
    <body>
    <h2>Ajax Post to PHP and Get Return Data</h2>
    <input name="myBtn" type="submit" value="Check" onclick="ajax_post()"> <br><br>
    <center> <p id="data" style="color:black"></p><br><br> </center>
    </body>
    </html>
    

    allNames:

    <?php
    // Get the string from the URL
    $json = file_get_contents('http://5dd559d3ce4c300014402cb8.mockapi.io/onboard/posts');
    $decodedJson = json_decode( $json, TRUE );
    $dataToPrint = array(
        'id',
        'createdAt',
        'name',
        'avatar',
        'jobDescription'
    );
    $returningString = "";
    foreach ( $decodedJson as $dataToDisplay ) {
        if ( is_array( $dataToDisplay ) && ! empty( $dataToDisplay ) ) {
            $printSeparator = FALSE;
            foreach ( $dataToDisplay as $key => $value ) {
                if ( array_search( $key, $dataToPrint ) !== FALSE ) {
                    $printSeparator = $printSeparator || TRUE;
                    $returningString .= "{$key}: {$value} <br/>";
                }
            }
            // Printed all from current, adding a HR or extra line break. Change as desired
            if ( $printSeparator ) {
                $returningString .= "<hr>";
            }
        }
    }
    
    echo $returningString;
    
    评论

报告相同问题?

悬赏问题

  • ¥50 易语言把MYSQL数据库中的数据添加至组合框
  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况