一尘不染

如何在PHP中解码JSON字符串?

json

我有一个看起来像这样的JSON字符串:

{"addresses":{"address":[{"@array":"true","@id":"888888","@uri":"xyz","household":{"@id":"44444","@uri":"xyz"},"person":{"@id":"","@uri":""},"addressType":{"@id":"1","@uri":"xyz","name":"Primary"},"address1":"xyz","address2":null,"address3":null,"city":"xyz","postalCode":"111111"}]}}

什么是解码此和地点PHP address1address2address3city,和postalCode到会话变量?

到目前为止,我已经尝试过了,但是没有用:

$results = json_decode(strstr($address, '{"addresses":{"address":[{'), true);
$_SESSION['address1'] = $results['address']['address1'];

谢谢!


阅读 217

收藏
2020-07-27

共1个答案

一尘不染

print_r 是您了解JSON结构的朋友。

<?php

$addresses = json_decode('{"addresses":{"address":[{"@array":"true","@id":"888888","@uri":"xyz","household":{"@id":"44444","@uri":"xyz"},"person":{"@id":"","@uri":""},"addressType":{"@id":"1","@uri":"xyz","name":"Primary"},"address1":"xyz","address2":null,"address3":null,"city":"xyz","postalCode":"111111"}]}}');

$_SESSION['address1'] = $addresses->addresses->address[0]->address1;
$_SESSION['address2'] = $addresses->addresses->address[0]->address2;
$_SESSION['address3'] = $addresses->addresses->address[0]->address3;
$_SESSION['city'] = $addresses->addresses->address[0]->city;
$_SESSION['postalCode'] = $addresses->addresses->address[0]->postalCode;

print_r($_SESSION);

结果是:

Array
(
    [address1] => xyz
    [address2] => 
    [address3] => 
    [city] => xyz
    [postalCode] => 111111
)
2020-07-27