0

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>
6
  • You mean that you'd like to print each array and add a couple of empty lines between them? Commented Nov 27, 2019 at 18:59
  • pretty much yeah, so each of the 7 elements in each index prints below each other, preferably with a tag so you know what they are, with a few spaces between each index Commented Nov 27, 2019 at 19:06
  • You could add echo '<br>'; at the end of your for loop and that will add a blank row in the browser where you're echoing your results. You can echo variables inside an actual HTML page if you'd like to format it any way you want. Can you be more specific in your question please? Commented Nov 27, 2019 at 19:09
  • Ah, I see, you'd like to print each element individually. Couldn't you simply do something like echo $obj[$i]["userIpAddress"]; . '<br>' for example? Repeat that for each element in the array? Commented Nov 27, 2019 at 19:12
  • I could have done that inside the PHP file which would have worked, but, I found out that I am required to send all the information in an array and get it to print like that inside the index.php file Commented Nov 27, 2019 at 19:14

1 Answer 1

2

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;
Sign up to request clarification or add additional context in comments.

11 Comments

hi, thanks for commenting. I am attempting this at the moment and am not getting very far with it, do you see what it is I am attempting to do?
Your question seems a bit confusing, could you post an example output and then I can help you display it with with the mock json data used in your example? @PaPaB1nG0
yeah sure, sorry for the confusion. my head is fried from trying to do this. ill post an example now
Ok, no problem @PaPaB1nG0. I can adjust it, and Ill make it clean and edit my example to explain a bit more.
thank you so much for all your help, its finally looking like i was trying to get it for the last few hours
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.