How to get JSON record value without actually knowing the field parameters in PHP

Viewed 20

I am working with Helloworks API and code below correctly and successfully prints JSON record for name, email and age via curl in PHP:

$response='{"data":{"audit_trail_hash":"ba8b9942b55e4e0fdad66a43cc4be257a4dfc3b632d594b690a2ecc2ea5ae8ef","data":{"form_Hpp8Ml":{"field_DMoHYX":"nancy","field_vprQI8":"nancy@gmail.com" ,"field_bvc876":"24 years"}},"document_hashes":{"form_Hpp8Ml":"ab906e7f19810e47559c45b3a43b4647b9d567c2b90acb8581c10d4e6fd51bb8"},"id":"aBQm8GHZcsjF64TD","metadata":null,"mode":"live","status":"completed","workflow_id":"OcoAStmswMbrEem2"}}
';

$json = json_decode($response, true);
 // print_r($json);

echo "<br><br>";

echo $name= $json["data"]["data"]["form_Hpp8Ml"]["field_DMoHYX"];
echo $email= $json["data"]["data"]["form_Hpp8Ml"]["field_vprQI8"];
echo $age= $json["data"]["data"]["form_Hpp8Ml"]["field_bvc876"];

Here is my issue. The following 4 Field form_Hpp8Ml, field_DMoHYX, field_vprQI8, field_bvc876 is always a random field as returned by Helloworks.com API for various users inputs. I do not want to continue editing those 4 listed field params any time I want to display records.

Is there any other way of getting records for name, email and age by bypassing or manipulating those 4 random field params listed above dynamically?

1 Answers

You could make use of PHP's function array_values to change the "data" array from an associative array to a numeric array.

Then you have to rely on the order of the fields. Are you able to do that?

If would look like this:

<?php
$response='{"data":{"audit_trail_hash":"ba8b9942b55e4e0fdad66a43cc4be257a4dfc3b632d594b690a2ecc2ea5ae8ef","data":{"form_Hpp8Ml":{"field_DMoHYX":"nancy","field_vprQI8":"nancy@gmail.com" ,"field_bvc876":"24 years"}},"document_hashes":{"form_Hpp8Ml":"ab906e7f19810e47559c45b3a43b4647b9d567c2b90acb8581c10d4e6fd51bb8"},"id":"aBQm8GHZcsjF64TD","metadata":null,"mode":"live","status":"completed","workflow_id":"OcoAStmswMbrEem2"}}';

$json = json_decode($response, true);

$data = array_values($json["data"]["data"]);
$fields = array_values($data[0]);

echo $name = $fields[0];
echo $email = $fields[1];
echo $age = $fields[2];
Related