简体   繁体   English

PHP 访问 json object 内的数组

[英]PHP accessing array within json object

I created a JSON object in JQuery that looks like this:我在 JQuery 中创建了一个 JSON object ,如下所示:

var massUpdateDetails = {
  checkone: $('#checkone').val(),
  checktwo: $('#checktwo').val(),
  details: [{
    detailone: $('#detailone').val(),
    detailtwo: $('#detailtwo').val()
  }],
  locs: [{
    locone: $('#locone').val(),
    loctwo: $('#loctwo').val()
  }]
}

When I post the massUpdateDetails object to PHP, I can print out the object like this:当我将 massUpdateDetails object 发布到 PHP 时,我可以像这样打印出 object:

<?php
  if(isset($_POST['massUpdateDetails'])){
    $value = $_POST['massUpdateDetails'];
  }

  print_r($value);
?>

When using print_r($value), here is what I am seeing:使用 print_r($value) 时,我看到的是:

Array
(
  [checkone] => checkoneInfo
  [checktwo] => value1,value2
  [details] => Array
    (
        [0] => Array
            (
                [detailone] => details of one
                [detailtwo] => details of two
            )

    )
  [locs] => Array
    (
      [0] => Array
            (
                [locone] => loc one
                [loctwo] => loc two
            )
     )
 )

I'm trying to set the various values to PHP variable like this:我正在尝试将各种值设置为 PHP 变量,如下所示:

$checkone= isset($value['checkone']) ? $value['checkone'] : ''; // <-- no problem getting this set

$detailone = isset($value['details']['detailone']) ? $value['details']['detailone'] : ''; // <-- problem is here

echo $detailone;

As you see in the above, I am having a problem setting the variable for $detailone.正如您在上面看到的,我在为 $detailone 设置变量时遇到问题。

When I echo $detailone, I get no error in the console.当我回显 $detailone 时,控制台中没有错误。

What am I doing wrong and how can I fix it?我做错了什么,我该如何解决?

$value['details'] is an array, so you have to access each element as an array element, eg $value['details'][0]['detailone'] $value['details']是一个数组,因此您必须将每个元素作为数组元素访问,例如$value['details'][0]['detailone']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM