循环遍历PHP中的对象数组

时间:2018-07-10 14:43:23

标签: javascript php jquery json

我正在用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()
  });
});

我通过

将此数组发布到PHP文件中
$('<input type="hidden" name="jsonLab"/>').val(jsonLab).appendTo('#bill_print');
$("#bill_print").submit(); 

在我的PHP文件中

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

我使用foreach的方式似乎出现了一些错误,或者它的格式不正确,而JSON没有被PHP解码。我不想使用AJAX进行提交。

1 个答案:

答案 0 :(得分:3)

问题在于此电话:

.val(jsonLab)

jsonLab是JS中保存的对象的数组。因此,将其设置为jQuery对象的val()将意味着在其上调用toString()。其结果是[object Object]。这就是发送到您的PHP逻辑的内容,因此是错误。

要解决此问题,您需要在将JSON设置为文本字段的值时手动对其进行字符串化:

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

还要注意,您可以对map()元素使用单个#selected_tests tr调用,而不是选择然后推送到显式实例化的数组:

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