У меня строка 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, чтобы декодировать это и помещать postalCode
, address2
, address3
, city
и postalCode
в переменные сеанса?
Пока я это пробовал, но он не работает:
$results = json_decode(strstr($address, '{"addresses":{"address":[{'), true); $_SESSION['address1'] = $results['address']['address1'];
Благодаря!
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 )
json_decode будет декодировать строку в формате json в PHP- объект .
Попробуй это:
$results = json_decode($address); $results['address1'] = $results->addresses->address[0]->address1; $results['address2'] = $results->addresses->address[0]->address2; $results['address3'] = $results->addresses->address[0]->address3; $results['city'] = $results->addresses->address[0]->city; $results['postalCode'] = $results->addresses->address[0]->postalCode;
Изменить – обновлено, я сначала неправильно разобрал ваш JSON.
Обратите внимание, что эти поля «@array» и «@id» являются недопустимыми нотами JSON, и технически они приводят к неуказанному поведению в парсерах JSON.
Почему бы не декодировать всю строку JSON, а затем получить то, что вам нужно?
$address = '{"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"}]}}'; $results = json_decode($address, true); $address = $results['addresses']['address'][0]; print $address['address1']; print $address['address2']; print $address['postalCode'];
Возможно, попробуйте $ results ['addresses'] ['address'] ['address1'];
Не знаете, почему вы используете strstr. но похоже, что это ничего не изменит в этом случае.
вы можете использовать print_r для вывода $ results, чтобы узнать, как выглядит объект.
Если вы выполняете print_r вашего массива, вы видите, как выглядит макет:
stdClass Object ( [addresses] => stdClass Object ( [address] => Array ( [0] => stdClass Object ( [@array] => true [@id] => 888888 [@uri] => xyz [household] => stdClass Object ( [@id] => 44444 [@uri] => xyz ) [person] => stdClass Object ( [@id] => [@uri] => ) [addressType] => stdClass Object ( [@id] => 1 [@uri] => xyz [name] => Primary ) [address1] => xyz [address2] => [address3] => [city] => xyz [postalCode] => 111111 ) ) ) )
json_decode ($ jsonData) возвращает объект btw, а не массив.
Например:
stdClass Object ( [addresses] => stdClass Object ( [address] => Array ( [0] => stdClass Object ( [@array] => true [@id] => 888888 [@uri] => xyz [household] => stdClass Object ( [@id] => 44444 [@uri] => xyz ) [person] => stdClass Object ( [@id] => [@uri] => ) [addressType] => stdClass Object ( [@id] => 1 [@uri] => xyz [name] => Primary ) [address1] => xyz [address2] => [address3] => [city] => xyz [postalCode] => 111111 ) ) ) )
Способы доступа к данным:
$object = json_decode($jsonString); $object->addresses->address[0]; // First address object $object->addresses->address[0]->{"@array"}; // Not good way to access object property (damn @) $object->addresses->address[0]->address1; $object->addresses->address[0]->addressType->{"@id"}; // Again damn @
:$object = json_decode($jsonString); $object->addresses->address[0]; // First address object $object->addresses->address[0]->{"@array"}; // Not good way to access object property (damn @) $object->addresses->address[0]->address1; $object->addresses->address[0]->addressType->{"@id"}; // Again damn @
:$object = json_decode($jsonString); $object->addresses->address[0]; // First address object $object->addresses->address[0]->{"@array"}; // Not good way to access object property (damn @) $object->addresses->address[0]->address1; $object->addresses->address[0]->addressType->{"@id"}; // Again damn @
:$object = json_decode($jsonString); $object->addresses->address[0]; // First address object $object->addresses->address[0]->{"@array"}; // Not good way to access object property (damn @) $object->addresses->address[0]->address1; $object->addresses->address[0]->addressType->{"@id"}; // Again damn @
Этот будет помещать все скалярные и нулевые значения в сеанс, где ключ не начинается с @
$jsonString = '{"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"}]}}'; $result = json_decode($jsonString); // will put *all* scalar and null values into session where key does not begin with a @ foreach($result->addresses->address[0] as $key=>$value) { if (substr($key, 0, 1) != '@' && (is_scalar($value) || is_null($value)) ) { $_SESSION[$key] = $value; } } print_r($_SESSION); ?>