简体   繁体   English

如何从json对象获取值到php数组

[英]How to get values from json object to php array

I am writing a php file for an application that allows the user to print a project report (with fpdf library).我正在为允许用户打印项目报告(使用 fpdf 库)的应用程序编写 php 文件。

The aim is to get datas from a db and then to build the PDF file dynamically.目的是从数据库中获取数据,然后动态构建 PDF 文件。

The datas are stored in json.数据存储在 json 中。

It is ok for almost all datas, but there are some that I can't reach.几乎所有数据都可以,但有些我无法达到。 Here is an example : First of all I already did this :这是一个例子:首先,我已经这样做了:

$Array['roof_coordinates'] = json_decode($Array['roof_coordinates'], false);

To get the number "nb" of "A523500" I'm doing like that :要获得“A523500”的数字“nb”,我这样做:

$Array['roof_coordinates']->results->packingList->total->A523500->nb;

What am I doing wrong ?我究竟做错了什么 ?

  "roofCoordinates": {

    "results": {

      "packingList": {

        "total": {

          "A523500": {

            "ref": "STRA523500",
            "nb": 16

          },
          "A523120": {

            "ref": "STRA523120",
            "nb": 0

          },
          "A522100": {

            "ref": "STRA522100",
            "nb": 8

          },

        },

      }

    },

}

And I tried to pass "true" to json_decode to convert objects to associative array but it doesn't seems to work...我试图将“true”传递给 json_decode 以将对象转换为关联数组,但它似乎不起作用......

Any help will be great !任何帮助都会很棒! Thank you in advance ;)先感谢您 ;)

Make sure you are accessing the resulting data structure correctly, it should work whether you decode to an array or an object.确保您正确访问结果数据结构,无论您解码为数组还是对象,它都应该有效。

<?php
$json = <<<END
{
  "roofCoordinates": {
    "results": {
      "packingList": {
        "total": {
          "A523500": {
            "ref": "STRA523500",
            "nb": 16
          },
          "A523120": {
            "ref": "STRA523120",
            "nb": 0
          },
          "A522100": {
            "ref": "STRA522100",
            "nb": 8
          }
        }
      }
    }
  }
}
END;

$arrayResults = json_decode($json, true);
$nbFromArray = $arrayResults['roofCoordinates']['results']['packingList']['total']['A523500']['nb'];

$stdClassResults = json_decode($json);
$nbFromStdClass =  $stdClassResults->roofCoordinates->results->packingList->total->A523500->nb;

assert($nbFromArray==16, 'Value should equal 16');
assert($nbFromArray==$nbFromStdClass, 'Values from either json_decode method should be equal');

echo 'From array: '.$nbFromArray.PHP_EOL;
echo 'From stdClass: '.$nbFromStdClass.PHP_EOL;

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

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