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>
Charlie Ansell
  • 451
  • 1
  • 7
  • 22
  • You mean that you'd like to print each array and add a couple of empty lines between them? – Paulo Hgo Nov 27 '19 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 – Charlie Ansell Nov 27 '19 at 19:06
  • You could add `echo '
    ';` 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?
    – Paulo Hgo Nov 27 '19 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"]; . '
    '` for example? Repeat that for each element in the array?
    – Paulo Hgo Nov 27 '19 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 – Charlie Ansell Nov 27 '19 at 19:14
  • That code has been plagiarised. There is a common source or it is from [this answer](https://stackoverflow.com/questions/15617512/get-json-object-from-url). For instance, the ***exact*** phrase *"`// In the case of this input, do key and array lookups to get the values`"*. – Peter Mortensen Mar 18 '23 at 14:17

1 Answers1

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;
Ice76
  • 1,143
  • 8
  • 16
  • 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? – Charlie Ansell Nov 27 '19 at 19:32
  • 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 – Ice76 Nov 27 '19 at 19:34
  • yeah sure, sorry for the confusion. my head is fried from trying to do this. ill post an example now – Charlie Ansell Nov 27 '19 at 19:37
  • Ok, no problem @PaPaB1nG0. I can adjust it, and Ill make it clean and edit my example to explain a bit more. – Ice76 Nov 27 '19 at 19:58
  • @PaPaB1nG0 See my changes! – Ice76 Nov 27 '19 at 20:06
  • thanks for that, the reason why I am printing it in the index.php file though is because I have to print it all through that page. thats why im messing around with encoding the array and sending it through – Charlie Ansell Nov 27 '19 at 20:10
  • can you see if there is any way to print like i am trying to do through the index.php page – Charlie Ansell Nov 27 '19 at 20:13
  • @PaPaB1nG0 there is a way. Can you do a brief summary of what the whole thing is supposed to do? Like, do you click a button, then print the json response? Or are you supposed to send data to index.php and then print the formatted response? – Ice76 Nov 27 '19 at 21:37
  • so yeah pretty much, I send the encoded array from my allNames.php class which has everything i need to print in it. that goes over to the index.php class and once you click the check button, the ajax_post function sets the text of the data text field to be the formatted data, or it should be doing that – Charlie Ansell Nov 27 '19 at 21:46
  • @PaPaB1nG0 See changes, the formatting on output may need to be changed, but I will leave that up to you – Ice76 Nov 27 '19 at 22:03
  • 1
    thank you so much for all your help, its finally looking like i was trying to get it for the last few hours – Charlie Ansell Nov 27 '19 at 22:10