简体   繁体   中英

PHP accessing array within json object

I created a JSON object in JQuery that looks like this:

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:

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

  print_r($value);
?>

When using print_r($value), here is what I am seeing:

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:

$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.

When I echo $detailone, I get no error in the console.

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']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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