dongmu6578 2016-06-28 03:02
浏览 67

在PHP中解析JSON_Decoded数组

I am passing data to an ajax call that has been 'json_stringified'. I am able to pass the data to PHP, however when trying to access the items within the passed array, I receive the following error:

'Trying to get property of non-object'

I've tried several things, but I am stuck. Can someone please assist? My code is below:

js:

    $.ajax({
        url: 'http://localhost/VibeSetter/services/getlocationsFavs.php',
        dataType: 'json',
        type: "POST",               
        data: {favs: JSON.stringify(localStorage.getArray("myFavs"))},
        success: function(data, status)
        {
            $.each(data, function(i,item)
            { 
                //pass to function to fill array
                      populateLocationsArray(i+1, item.idlocations,item.name,item.longitude, item.latitude);

            });
        },

         error: function(jqXHR, textStatus, errorThrown)
        {
            console.log(arguments);
        //  alert('HTTP Error: '+errorThrown+' | Error     Message:'+textStatus);

        }
    });

}

console.log(localStorage.getArray("myFavs")) returns:

{locations: 1},{locations: 0},{locations: 4293315}

php:

<?php
  header('Content-type: application/json');

  include 'config.php';
  $data = json_decode($_POST['favs']);
  var_dump($data);

  foreach($data as $d)
  {
      print $d->locations;
  }

  ?>

which returns the following in chrome developer tools pane:

array(3) {
  [0]=>
  string(14) "{locations: 1}"
  [1]=>
  string(14) "{locations: 0}"
  [2]=>
  string(20) "{locations: 4293315}"
  }


Notice: Trying to get property of non-object in C:\xampp\htdocs\VibeSetter\services\getlocationsFavs.php on line 10

Notice: Trying to get property of non-object in C:\xampp\htdocs\VibeSetter\services\getlocationsFavs.php on line 10

Notice: Trying to get property of non-object in C:\xampp\htdocs\VibeSetter\services\getlocationsFavs.php on line 10

Can someone please tell me how to access each element of this array? The idea is to parse each 'location' value and concatenate the locations in a query further in the code as specific values in a query search.

Thanks in advance

  • 写回答

1条回答 默认 最新

  • dtwxmn8741 2016-06-28 03:29
    关注

    Considering $_POST['favs'] have value as '[{"locations": "1"},{"locations": "0"},{"locations": "4293315"}]';

    Then,

    $array = json_decode($_POST['favs'],TRUE);
    foreach($array as $d)
    {
        print $d['locations'];
    }
    

    When TRUE, returned objects will be converted into associative arrays.

    Reference

    评论

报告相同问题?

悬赏问题

  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝