0

I have really been struggling with outputting the content of a json data I received from a rest API response correctly. I have searched a lot and tried different ways but I noticed everyone's is always unique...below is my code..specifically of consideration is the "headers_field" it is an array with a lot of values and keys...and I want to also output these values with the keys...While the ("data") has two values with it...below is what I have tried also but I am just getting the first result from the loop while it returns ("headers_field": Array), ("box: Array")..I used Curl. Kindly look below. Thanks.

{
"data": [
    {
        "approved": null,
        "approved_user_id": null,
        "boxes": [],
        "created": "2020-05-19T21",
        "created_at": "2020-05-19T21",
        "edited": null,
        "edited_in_affiliate": null,
        "edited_in_hdr": null,
        "edited_in_web_app": null,
        "erp_project_id": null,
        "error_description": "",
        "header_fields": [
            {
                "boxes": [],
                "code": "creditor_number",
                "data_type": "",
                "error": "",
                "feature_id": nvnnn,
                "value": "hhhhh"
            },
            {
                "boxes": [],
                "code": "payment_account_number",
                "data_type": "",
                "error": "",
                "value": ""
            },
            {
                "boxes": [],
                "code": "order_number",
                "data_type": "",
                "error": "",
                "value": ""
            },
            {
                "boxes": [],
                "code": "total_amount_incl_vat",
                "data_type": "",
                "error": "",
                "feature_id": mmm
                "value": "hhh"
            },
   {
        "approved": null,
        "approved_user_id": null,
        "boxes": [],
        "created": "2020-05-19",
        "created_at": "2020-05-19",
        "edited": null,
        "edited_in_affiliate": null,
        "edited_in_hdr": null,
        "edited_in_web_app": null,
        "erp_project_id": null,
        "error_description": "",
        "header_fields": [
            {
                "boxes": [],
                "code": "reference",
                "data_type": "",
                "error": "",
                "value": ""
            },
            {
                "boxes": [],
                "code": "payment_swift_bic",
                "data_type": "",
                "error": "",
                "value": ""
            },

            {
                "boxes": [],
                "code": "recipient_vat_reg_no",
                "data_type": "",
                "error": "",
                "value": ""
            },

            {
                "boxes": [],
                "code": "joint_payment_id",
                "data_type": "",
                "error": "",
                "value": ""
            },

            {
                "boxes": [],
                "code": "catalog_debitor_id",
                "data_type": "",
                "error": "",
                "value": ""
            },

            {
                "boxes": [],
                "code": "case_number",
                "data_type": "",
                "error": "",
                "value": ""
            },


            {
                "boxes": [],
                "code": "payment_account_number",
                "data_type": "",
                "error": "",
                "value": ""
            },
            {
                "boxes": [],
                "code": "payment_iban",
                "data_type": "",
                "error": "",
                "value": ""
            }


      ],
        "id": 00000,
        "image": "https://skkkkkllllllllll
        "line_items": [],
        "note": "",
        "organization_id": 11111,
        "organization_voucher_id": 7777,
        "page_count": 1,
        "status": "successful",
        "type": "voucher",
        "upload_type": "affiliate",
        "uploaded_by_user_id": 0000001
        "user_payment_method": "",
        "user_voucher_type": ""
   }
   ],
    "meta": {
    "count": 2
   }
   }

MY LOOP OPERATION

  .....
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $request);
curl_setopt($ch,CURLOPT_HTTPHEADER,$headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$results= curl_exec($ch);

   $g= json_decode($results, true);

   $i=0;
  $g_length =count($g["data"]);//to count through the child array

  for ($i=0; $i < ($g_length);$i++)
   {

      $k= $g["data"][$i]; //asssigning the array position to a variable

      foreach($k as $mydata=>$mvalue) {
    $hey = trim($mvalue); //Removes white spaces
    if ($mvalue !=="")
    echo $mydata. " : " . $mvalue . "<br>"; 

    else

    echo "This is empty. <br/>";


    ///////////////////////////////////////////
    foreach($mvalue as $lkey=>$lvalue)
    {
    $u=is_array($mvalue);
    if(($u) and !empty($u))
    echo $lkey. ":" . $lvalue. "<br>";
    else

    echo "what? <br/>";
    ///////////
    foreach($lvalue as $okey=>$ovalue)
    {

    echo $okey. ":". $value. "</n>";
    /////
 foreach($ovalue as $key=>$value)
 {
      $v=is_array($value);
      if(($v) and !empty($v))
      echo $key. ":" . $value. "<br>";
      else
    echo "hello";
      //print_r($key);

      /////
  }
    }
    //////////
  }

  //////////////////////////////////////////
 }
Dlaw
  • 131
  • 2
  • 14
  • I understand that you honestly tried to solve this problem and that you needed help. However, "snowflake questions" (_"everyone's is always unique"_) on this topic are posted here many times daily. Stack Overflow is over-saturated with these questions of "how to iterate this multi-dimensional array" and these questions (as you admitted) are doing very little to aid future researchers. For this reason, there is little value in Stack Overflow retaining hundreds of these questions. – mickmackusa May 21 '20 at 21:10
  • If you wanted specific values instead of every piece of data, then a more specific/narrow answer could have been provided to you. This is the reason why Toby's answer is for general-use and less about helping you access named key data specifically. For developers who need to "open up" and display `Array()` output, the solution is to very simply loop the data belonging to that specific key. There is nothing wrong with exploring your data with successive waves of loop-n-print until you get what you need. – mickmackusa May 21 '20 at 21:26
  • Food for thought: https://3v4l.org/g7CMX – mickmackusa May 21 '20 at 22:15
  • I saw the two links you associated my question with; well to be honest they; didn't help matters especially to someone who is new to matter of this sort. If they did answered the question as it was answered here on a general deeper and simpler note I would have understood it and used them. That is why I am so grateful to @Toby Harris for simplifying it in the most basic terms. I however appreciate the last link you sent too..That is quite a lot. Thanks. – Dlaw May 22 '20 at 10:35

1 Answers1

0

Provided you know how deep the array is that you get back from the API or how many dimensions and you know the key structure will be the same you could use something like this:

NOTE: I took your JSON and did a quick and dirty to spit out all the keys and values - including the nested header fields. Essentially its based on whether the value is an ARRAY. If you know the structure you are expecting you could make this more elegant by creating an array map and a function to process all vals that are sub arrays.

Anyway - I hope the below helps you as a starter:

foreach($theDecodedData['data']["header_fields"] as $row){

    foreach($row as $key => $val){

        if(!is_array($val)){

            echo "$key: $val \n";
        }
        else{
             echo "Contents of $key \n";
            foreach($val as $vkey => $vval){

                if(!is_array($vval)){

                    echo "$vkey: $vval \n";
                }
                else{

                    echo "Contents of $vkey \n";
                    foreach($vval as $vvvkey => $vvvval){
                        if(!is_array($vvvval)){

                            echo "$vvvkey: $vvvval \n";
                        }
                        else{

                            echo "Contents of $vvvkey \n";
                            foreach($vvvval as $vvvvkey => $vvvvval){

                                echo "$vvvvkey: $vvvvval \n";
                            }
                        }
                    }
                }
            }
        }
    }
}
  • Thank you so much, this helps a lot. From here I can operate on the keys and values. For others who might want to learn from this also up there in my question I didn't emphasis on the ("data") as an array I just used it literally without putting it in quotation marks.. so I was finding it difficult to use @Toby Harris answer because he had used "headers_fields" instead of "data"..lol my bad... Hey, if you find some time later; kindly edit the "headers_field" to "data" in your answer. Thank you so much. – Dlaw May 21 '20 at 10:07
  • Cool, I'm glad I could help. As I say - its a basis on which to build something more elegant. I have edited my code to include the data key. I tested it and it does work. Good luck with your project! – Toby Harris May 21 '20 at 20:57
  • Yes, recursion would be far more succinct and therefore much more elegant. – mickmackusa May 21 '20 at 21:26