Access nested JSON value with PHP using object/arrow syntax - php

I have read a dozen stack posts on this topic and none of them work given my decoded JSON string. Here is my JSON:
{
"id":"cus_EfVGU7XtvtKUx2",
"account_balance":0,
"cards":{
"count":1,
"data":[
{
"id":"card_1ECAFn2H1YALOWTjH0zGfOS7",
"exp_month":11,
"exp_year":2019,
"last4":"1111",
"metadata":[
],
"name":"ned land",
"type":"Visa"
}
]
},
"invoice_prefix":"5F8A134",
"has_more":false,
"total_count":1,
"url":"\/v1\/customers\/cus_EfVGU7XtvtKUx2\/sources"
}
Then I encode that string into an object:
$obj = json_decode($json, false);
I can easily get that top-most id value by doing this:
$obj->id
But when I try to get the exp_month value, I get back an empty string:
$expMonth = $obj->cards->data->exp_month;
Then alternatively I try array syntax:
$obj = json_decode($json, true);
$expMonth = $obj["cards"]["data"]["exp_month"];
And again $expMonth resolves to an empty string. What am I doing wrong?

Use $expMonth = $obj->cards->data[0]->exp_month;. $data is an array.
Full example:
$obj = json_decode('{
"id":"cus_EfVGU7XtvtKUx2",
"account_balance":0,
"cards":{
"count":1,
"data":[
{
"id":"card_1ECAFn2H1YALOWTjH0zGfOS7",
"exp_month":11,
"exp_year":2019,
"last4":"1111",
"metadata":[
],
"name":"ned land",
"type":"Visa"
}
]
},
"invoice_prefix":"5F8A134",
"has_more":false,
"total_count":1,
"url":"\/v1\/customers\/cus_EfVGU7XtvtKUx2\/sources"
}');
print_r($obj->cards->data[0]->exp_month);
Output is 11.

data is an array of objects.
$obj->cards->data[0]->exp_month
should do the job

Related

merge Array of objects into array with unique object

I have a array of various object, but I need turn this objects into unique object. Below I share my code.
$result = [];
$idiomas = Idioma::all()->toArray();
foreach ($idiomas as $lang) {
$result[] = [
$lang['palavra_chave'] => $lang[$id]
];
}
return response()->json($result);
reponse
[
{ "INICIAL": "Inicial"},{ "RELATORIOS": "Relatórios"},{ "FUNCIONARIO": "Funcionário"},{ "DATA": "Data"},{ "ANEXAR_IMAGEM": "Anexar imagem"},{ "DISCIPLINA": "Disciplina"}
]
But I need transform this objects into one, like this
[
{
"INICIAL": "Inicial",
"RELATORIOS": "Relatórios",
"FUNCIONARIO": "Funcionário",
"DATA": "Data",
"ANEXAR_IMAGEM": "Anexar imagem",
"DISCIPLINA": "Disciplina"
}
]
anyone can help me?
$idiomas = Idioma::all()->toArray();
if (count($idiomas)) {
//$result = new stdClass; # wouldn't work without base namespace
$result = new \stdClass;
foreach ($idiomas as $lang) {
$result->{$lang['palavra_chave']} = $lang[$id];
}
return response()->json([$result]);
}
// otherwise
Edit: #Tpojka's answer definitely looks more appropriate. Use the following one only if you can't change the way you retrieve data initially (I'm not familiar enough with Laravel).
The following should work:
// Take your initial JSON
$input = <<<JSON
[
{ "INICIAL": "Inicial"},{ "RELATORIOS": "Relatórios"},{ "FUNCIONARIO": "Funcionário"},{ "DATA": "Data"},{ "ANEXAR_IMAGEM": "Anexar imagem"},{ "DISCIPLINA": "Disciplina"}
]
JSON;
// Transform it into a PHP array
$input_as_array = json_decode($input);
// Reduce it into an associative array
$associative_array = array_reduce($input_as_array, function($associative_array, $item) {
return $associative_array += (array)$item;
}, []);
// Encode it back into JSON, as an array
$result = json_encode([$associative_array], JSON_PRETTY_PRINT);

How to iterate the JSON data into a loop using PHP?

I need to iterate some JSON formatted data into loop using PHP. My JSON data is below:
{
"question1":{
"ques":"questin1",
"optional":[
{
"opt":"option1"
},
{
"opt":"option2"
}
]
},
"question2":{
"ques":"questin2",
"optional":[
{
"opt":"option1"
},
{
"opt":"option2"
}
]
}
}
I need to run the loop so that the result data will come in above format using PHP.
Convert the php object to json object using json_encode
// convert object => json
$json = json_encode($myObject);
This might helpful: https://stackoverflow.com/a/9858457/6285410
What you showed us is a Possible JSON Data. In this Format, we can do nothing with it in PHP except by decoding back into Native PHP Object. Once that is done, You can access all the Properties of the Object like you do with normal PHP Object like $objData->questin1. Here's what is meant with the above statements:
<?php
$strJson = '{
"question1":{
"ques":"questin1",
"optional":[
{
"opt":"option1"
},
{
"opt":"option2"
}
]
},
"question2":{
"ques":"questin2",
"optional":[
{
"opt":"option1"
},
{
"opt":"option2"
}
]
}
}';
$objData = json_decode($strJson);
var_dump($objData);
// NOW, TO GET AT EACH OF THE PROPERTIES OF THE OBJECT IS EASY...
// ACCESS THE question1 OR question2
$q1 = $objData->question1;
$q2 = $objData->question2;
// ACCESS THE que WITHIN question 1 OR question2
$k1 = $objData->question1->ques; // EQUIVALENT TO: $q1->ques
$k2 = $objData->question2->ques; // EQUIVALENT TO: $q2->ques
// ACCESS THE optional ARRAY INSIDE OF question 1 OR question2
$opt1 = $objData->question1->optional; // EQUIVALENT TO: $q1->optional
$opt2 = $objData->question2->optional; // EQUIVALENT TO: $q2->optional
var_dump($q1, $q2, $k1, $k2, $opt1, $opt2);
?>

PHP - Append new JSON object to nested array within JSON object

Setup
I have retrieved a JSON string from a URL using 'file_get_contents' and have subsequently decoded it using `json_decode'
$search_URL="http://abcdefg.com"
$json = file_get_contents($search_URL);
$obj = json_decode($json, true);
The JSON represents an Apache Solr search response:
{
"responseHeader":{
"status":0,
"QTime":3,
"params":{
"q":"zzzzzzz",
"wt":"json"
}
},
"response":{
"numFound":20690,
"start":0,
"docs":[
{
"title":"yyyyy-y-y-yyyyy-yy-y",
"author":"author 1, author 2, author 3",
"url":"https://yyyyy.com",
"id":yyyy,
"_version_":yyyyy
},
{
"title":"xxxx-x-x-xxxx-xxxx",
"author":"author 1, author 2",
"url":"https://xxxxx.com",
"id":xxxxx,
"_version_":xxxxxx
},
]
}
}
I basically need to grab each author field in the docs[] array, split it by commas to get a new array
$author_array = explode(", ", $author);
I then need to call another web service with these author names that will return JSON. I would love to simply plug this JSON in to my existing JSON and send it all back
Question
I need to modify my JSON so that each doc contains this new JSON object. How can I do this?
{
"title":"xxxx-x-x-xxxx-xxxx",
"author":"author 1, author 2",
"url":"https://xxxxx.com",
"id":xxxxx,
"_version_":xxxxxx,
"authors":[
{
"name": "author1",
"id": "143"
},
{
"name": "author2",
"id": "72"
}
]
}
My Attempt
I have tried a simpler version of this where I simply have an array of author names
{
"title":"xxxx-x-x-xxxx-xxxx",
"author":"author 1, author 2",
"url":"https://xxxxx.com",
"id":xxxxx,
"_version_":xxxxxx,
"authors":[
"author1",
"author2"
]
}
I tried the following:
$response = $obj['response'];
$docs = $response['docs'];
foreach($docs as &$doc) {
$author = $doc['author'];
$authors_array = explode(" ,", $author);
$doc['authors'] = $authors_array;
}
This has ultimately failed as the new array is not appended.
Explode the author string, call the API on each element, make an array of all these results, and put it back into the object.
I use a reference below in foreach so it can modify the document element directly.
foreach ($obj['response']['docs'] AS &$doc) {
$author_names = explode(',', $doc['author']);
$author_array = array_map('author_api', $author_names);
$doc['authors'] = $author_array;
}

decode multiple json object php

I have this jsone that I need to convert in three different objects.
in some php. I know that i have to use json_decode but I only decode the first object , the others 2 object don't.
{
"recorrido":[
{
"lon":"-60.67216873168769",
"lat":"-32.9230105876913",
"date":"13/10/24-12:22:32",
"globaltime":"00:09",
"globalkm":0.0,
"speed":2.11,
"altitude":-32.9230105876913,
"groupId3":0,
"id":1,
"color":0,
"auxInt":0,
"groupId2":0,
"provider":1,
"groupId1":0,
"workoutid":1
},
{
"lon":"-60.67216873168769",
"lat":"-32.9230105876913",
"date":"13/10/24-12:22:35",
"globaltime":"00:12",
"globalkm":0.0,
"speed":2.11,
"altitude":-32.9230105876913,
"groupId3":0,
"id":2,
"color":0,
"auxInt":0,
"groupId2":0,
"provider":1,
"groupId1":0,
"workoutid":1
}
],
"user":{
"asunto":"",
"userId":1
},
"Itemout":{
"uploaded":"false",
"isSelected":false,
"id":1,
}
}
what do you sugest? the script must be in php. the object "recorrido" is a multiple array object.
wthout testing it, try somrting like this:
$tempArray = (array)$recorrido; // or how you cal your json object
foreach ($tempArray as $tempJson)
{
$myArray = json_decode($tempJson);
print_r($myArray);
}
You can use hardcode method if you have static json structure:
Show below
$result = json_decode($json);
$recorrido = $result->recorrido;
// And so on
In another way there is a workaround with arrays.
list($arr1, $arr2, $arr3) = json_decode($json, true);
This solution will make you three arrays of data from json.

Trying to fetch Json Result

I am trying to fetch the individual values from the obtained json result
{
"_total": 1,
"values": [{
"id": 123456,
"name": "Example Technologies "
}]
}
Now, I need to get the _total value. For that i am using
echo $res->_total;
which gives me
Notice: Trying to get property of non-object
If i try like
echo $res['_total'];
gives me
Warning: Illegal string offset '_total'
So, In what way, I can get the _total value.
Please help me in that. Thanks in advance!
Do this:
$obj = json_decode($res);
echo $obj->_total;
You need to decode the JSON data.
suppose data is
$data = '{"category_id":"10","username":"agent1","password":"82d1b085f2868f7834ebe1fe7a2c3aad:fG"}';
and you want to get particular parameter then
$obj = json_decode($data);
after
$obj->{'category_id'} , $obj->{'username'} , $obj->{'password'}
May be this help you !
It seems that you didn't json_decode() the JSON string, or $res is not the result of json_decode().
Example:
$json = '{
"_total": 1,
"values": [{
"id": 123456,
"name": "Example Technologies "
}]
}';
$res = json_decode($json);
echo $res->_total;
you will need to run the string through json_decode first http://uk3.php.net/json_decode
which will return an array.
Here is Your String,
$data = '{ "_total": 1, "values": [{ "id": 123456, "name": "Example Technologies " }] }';
$test = (array)json_decode($data);
echo '<pre>';
print_r(objectToArray($test));
die;
Function is here
function objectToArray($d) {
if (is_object($d)) {
// Gets the properties of the given object
// with get_object_vars function
$d = get_object_vars($d);
}
if (is_array($d)) {
/*
* Return array converted to object
* Using __FUNCTION__ (Magic constant)
* for recursive call
*/
return array_map(__FUNCTION__, $d);
}
else {
// Return array
return $d;
}
}
May be its help you!!

Categories