sai
sai

Reputation: 135

Loop over array of objects in PHP

I am creating an array of objects in jQuery.

var selected_tests = $("#selected_tests").find("tr");
jsonLab = [];
$.each(selected_tests, function() {
  jsonLab.push({
    test: ($(this).children()).eq(0).text(),
    amount: ($(this).children()).eq(1).text()
  });
});

I am posting this array to a PHP file by

$('<input type="hidden" name="jsonLab"/>').val(jsonLab).appendTo('#bill_print');
$("#bill_print").submit(); 

In my PHP file

if(isset($_POST['jsonLab']))
{
  $lab = json_decode($_POST['jsonLab'],true);
  foreach ($lab as $key => $value) {
    echo $value["test"] . ", " . $value["amount"] . "<br>";
  }   
}

There seems to be some mistake in the way I am using foreach or maybe it's incorrectly formatted JSON which isn't being decoded by PHP. I dont want to use AJAX for the submission.

Upvotes: 4

Views: 77

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

The issue is with this call:

.val(jsonLab)

jsonLab is an array of objects held in JS. As such, setting it to the val() of a jQuery object will mean toString() is called on it. The result of that is [object Object]. This is what's sent to your PHP logic, hence the error.

To fix this you need to manually stringify the JSON when you set it to the value of the text field:

$('<input type="hidden" name="jsonLab" />').val(JSON.stringify(jsonLab)).appendTo('#bill_print');

Also note that you can use a single map() call on the #selected_tests tr elements instead of selecting then pushing to an explicitly instantiated array:

var jsonLab = $("#selected_tests tr").map(function() {
  return {
    test: $(this).children().eq(0).text(),
    amount: $(this).children().eq(1).text()
  };
}).get();

Upvotes: 3

Related Questions