Loop through JSON array

I’m building an English test for a page on a friend’s site. There are 50 multiple choice questions, using radio buttons to select the answer. I want the answers to be emailed to him along with the person’s details so i’m using a PHP script. I can get the input text boxes values and assign them to variables to be passed to the PHP script no problem, I already built a successful contact form on the site but with no experience of writing PHP I just copied a template for getting form values and displaying them in an email

I’m using
var answers = $(":radio").serializeArray();

to get the answers as an array object so it looks like this

 [{ name: "question1",
    value: "don't know"
  { name: "question2",

How can I output the answers array in my PHP script?

I realise I need some kind of for or foreach loop but I’ve been unsuccessful so far in looping through the answers array and outputting it in the PHP script so I can output something like

Question 1: don’t know
Question 2: …

any help appreciated!

You can use JSON.stringify(yourArray) in javascript to convert it into a json string. After passing it to php you can use json_decode(yourJsonString) to convert it into a php array containing objects. Then you could use a foreach loop to output the contents.
Sample for the output:
foreach ($yourPhpArray as $item)
echo $item->name . " " . $item->value . “<br>”;

1 Like

Thanks for your help, it pointed me in the right direction. I had a bit more trial and error getting what I wanted but I got there in the end using

$phpArray = json_decode($answers, true);
$testAnswers = "";
foreach ($phpArray as $question) {
    $testAnswers .= $question['name'] . ": " . $question['value'] . "\n";

then plugging in $testAnswers in the email body along with the other form fields