Decode JSON (PHP) [duplicate] - php

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 6 years ago.
how can I select the number of "total_items" and the "average_price"?
JSON:
{
"status" : "success",
"data" : {
"items" : [
{
"market_hash_name" : "AK-47 | Redline (Field-Tested)",
"total_items" : 698,
"lowest_price" : "3.90",
"highest_price" : "300.00",
"cumulative_price" : "4669.62",
"recent_sales_info" : {
"hours" : "17.94",
"average_price" : "4.23"
}
}
]
}
}
Thats my PHP-Script:
$link = 'skin.json';
$string = file_get_contents($link);
$obj = json_decode($string, TRUE);
$name = $obj['items']['market_hash_name'];
$itmes = $name['total_items'];
$itmes = $name['average_price'];
How can I save the number of "total_items" and the "average_price" in variables?
Thank You
Regards.
Enge

Just like Andreas wrote, or :
// first, new variable (shorter lines/less depth afterwards)
$article = $obj['data']['items'][0];
// then
$total_items = $article['total_items'];
$avg_price = $article['recent_sales_info']['average_price'];
Enge, note that "items": [ is an opening array within JSON object, that's the zero You were missing...

Try this:
$total_items = $obj['data']['items'][0]['total_items'];
$avg_price = $obj['data']['items'][0]['recent_sales_info']['average_price'];

Related

how to access json file fields [duplicate]

This question already has answers here:
How to loop through PHP object with dynamic keys [duplicate]
(16 answers)
Closed 5 years ago.
{
"took" : 363,
"timed_out" : false,
"num_reduce_phases" : 15,
"_shards" : {
"total" : 7195,
"successful" : 7195,
"failed" : 0
},
"hits" : {
"total" : 35672,
"max_score" : 0.0,
"hits" : [ ]
},
"aggregations" : {
"2" : {
"doc_count_error_upper_bound" : 54,
"sum_other_doc_count" : 1463,
"buckets" : [
{
"key" : "ふるさと納税",
"doc_count" : 30376
}
]
}
}
}
This is the json file . I need to access the doc_count field.
I am trying to do it like this
$trend_words = json_decode($file);
$aggregations = $trend_words->aggregations;
$buckets = $aggregations->{2}->buckets->{0};
But its not working.
Can someone help.
$trend_words = json_decode($file,true);
$aggregations = $trend_words['aggregations']['2']['buckets'][0]['doc_count'];
print_r($aggregations)
You should use ,true otherwise you will get an stdclass object and not an array you want.
try this
<?php
$sJson = '
{
"took" : 363,
"timed_out" : false,
"num_reduce_phases" : 15,
"_shards" : {
"total" : 7195,
"successful" : 7195,
"failed" : 0
},
"hits" : {
"total" : 35672,
"max_score" : 0.0,
"hits" : [ ]
},
"aggregations" : {
"2" : {
"doc_count_error_upper_bound" : 54,
"sum_other_doc_count" : 1463,
"buckets" : [
{
"key" : "ふるさと納税",
"doc_count" : 30376
}
]
}
}
}
';
$aJson = json_decode($sJson, true);
echo $aJson['aggregations'][2]['buckets'][0]['doc_count'];
https://3v4l.org/kHfdo
Here is the answer, As the buckets increases you need to have a loop through to read all the buckets
$trend_words = json_decode($file, true);
$aggregations = $trend_words['aggregations'][2];
$buckets = array();
foreach($aggregations as $element)
$buckets[] = $element['buckets'];
print_r($buckets);
Make Json to array and try
$trend_words = json_decode($file, true);
$aggregations = $trend_words['aggregations'];
$buckets =$aggregations[2]['buckets'][0];

Mongodb Nested array value is empty always

Mongodb gives the following:
{
"_id" : ObjectId("55d1d8ea464498a8338b4567"),
"appuserfirstname" : "Bhatti",
"appuserlastname" : "Singh",
"appusermiddlename" : "Tripatpal",
"appuseremail" : "tripat.90#gmail.com",
"appusergoogleid" : [
{ "id" : "APA91bFPqNjK5bWdTe6bAniDV8ZlmG5vL3Q1qRz_WGAasOMu_WBbzoorWI2uCU7yC4IS-yggNGQvL7oUp5YhiejOC1TB4bFQspKj4AUZ05-IEL9DJiI2oNwIl5YwW5zyBVqrTMNWFF2B" }
],
"usercreationdate" : ISODate("2015-08-17T18:21:54Z"),
"status" : "0",
"userfollows" : [
{ "following" : ObjectId("55cd8dae46449867738b4567") }
]
}
I want the ids that are in following. but it always gives me empty string
<?php
$appuserid = '123456789';
$appuserscollection = $this->database->createCollection("appusers");
$followers = array('_id' => new MongoId($appuserid));
$s = "";
$result = $appuserscollection->find($followers);
foreach($result as $document) {
$s.=$document['userfollows'];
}
echo $s;
?>
With
$appuserscollection = $this->database->createCollection("appusers");
you create a new collection. And a new collection is always empty
you could try
$collection = new MongoCollection($this->database, 'appusers');

WordPress get json data single value

Trying to get the single value from google finances api. I can retrieve the data perfectly however when I try to echo out a single value it doesn't seem to work. Can anyone help?
My code is:
$request = wp_remote_get('http://www.google.com/finance/info?q=NASDAQ%3aGOOG', $args );
$price = wp_remote_retrieve_body( $request );
print_r($price);
The output is:
// [
{
"id": "304466804484872"
,"t" : "GOOG"
,"e" : "NASDAQ"
,"l" : "533.75"
,"l_fix" : "533.75"
,"l_cur" : "533.75"
,"s": "2"
,"ltt":"4:01PM EST"
,"lt" : "Dec 2, 4:01PM EST"
,"lt_dts" : "2014-12-02T16:01:56Z"
,"c" : "-0.05"
,"c_fix" : "-0.05"
,"cp" : "-0.01"
,"cp_fix" : "-0.01"
,"ccol" : "chr"
,"pcls_fix" : "533.8"
,"el": "533.00"
,"el_fix": "533.00"
,"el_cur": "533.00"
,"elt" : "Dec 2, 7:59PM EST"
,"ec" : "-0.75"
,"ec_fix" : "-0.75"
,"ecp" : "-0.14"
,"ecp_fix" : "-0.14"
,"eccol" : "chr"
,"div" : ""
,"yld" : ""
}
]
I've tried echoing out the single value, adding a foreach statement and then echoing out the value based on 'l_fix' and the 'id', and also tried splitting the string up but it wouldn't work.
Thanks
Do it:
$request = wp_remote_get('http://www.google.com/finance/info?q=NASDAQ%3aGOOG', $args );
$data = wp_remote_retrieve_body( $request );
$data = str_replace('//','',$data);
$data = json_decode($data);
$price = $data[0]; // $price = array_shift($data);
print $price->l_fix .....
Google APIs (in this specific case) return JSON with two first chars ('//').

Yii, MongoDB query Subdocuments for insertion in a Mysql Table

I'm doing a project using Yii Framework, MySQL and MongoDB. I need to get the data from a collection of the mongo database and insert the records in a mysql table. The document of mongodb has subdocuments and I need to insert a row in mysql for every subdocument in the collection. The code of my project is:
$query = array('year'=>'2014');
$records = Yii::app()->edmsMongoCollection('DocumentosDesgloseER')->find($query);
foreach($records as $data){
$success = false;
$model = new DesgloseAcumulado;
$atributos['Id_Enterprise'] = $data['id_enterprise'];
$atributos['Id_Store'] = $data['id_store'];
$atributos['Month'] = $data['month'];
$atributos['Year'] = $data['year'];
$atributos['Id_Usuario'] = Yii::app()->user->id;
$atributos['Id_RubroER'] = $data['DocumentosDesgloseER'][0]['id_rubroer'];
$i = $i + 1;
$model->attributes = $atributos;
if($model->save()) {
$success = true;
}
}
And the structure of my collection in mongodb is:
{
"_id" : ObjectId("535fe63acac5853943166f5c"),
"DocumentosDesgloseER" : [
{
"elemento" : "VENTAS NETAS",
"id_rubroer" : "45",
"id_documento_consolidados_temp" : "31809",
"abreviatura" : "VN",
"orden" : "1",
"formula" : "(250*CM)",
"tipo_fila" : "1",
"resultado_actual" : "113.628",
"resultado_ant" : "239.851",
"promedio_mensual_actual" : "111.365",
"ppto_mes_actual" : "131.540",
"real_acumulado_actual" : "556.826",
"real_acumulado_ant" : "965.824",
"ppto_acumulado_actual" : "666.805"
},
{
"elemento" : "RUBRO DE PRUEBAS",
"id_rubroer" : "19",
"id_documento_consolidados_temp" : "31810",
"abreviatura" : "RP",
"orden" : "3",
"formula" : "CM/500",
"tipo_fila" : "1",
"resultado_actual" : "71.057",
"resultado_ant" : "281.697",
"promedio_mensual_actual" : "67.090",
"ppto_mes_actual" : "72.347",
"real_acumulado_actual" : "335.448",
"real_acumulado_ant" : "879.719",
"ppto_acumulado_actual" : "366.743"
}
],
"documentoID" : "4DOTA2",
"id_enterprise" : "1",
"id_store" : "24",
"month" : "Importes2",
"year" : "2014",
"lastMonthNumber" : NumberLong(4)
}
This is only one of the documents in the collection. As I said earlier, I need to save a row for every subdocument for each document in the mysql database. My code save only the data of the document and the id_rubroer of the subdocument "0".
Does anyone know how I can make the For Loop for each subdocument rather than for each object (document)?
Thanks
Just for-loop the "sub-documents"... say:
foreach($records['DocumentosDesgloseER'] as $data){
$success = false;
$model = new DesgloseAcumulado;
$atributos['Id_Enterprise'] = $data['id_enterprise'];
$atributos['Id_Store'] = $data['id_store'];
$atributos['Month'] = $data['month'];
$atributos['Year'] = $data['year'];
$atributos['Id_Usuario'] = Yii::app()->user->id;
$atributos['Id_RubroER'] = $data['id_rubroer'];
$i = $i + 1;
$model->attributes = $atributos;
if($model->save()) {
$success = true;
}
}

how to parse json data in php

I have json result from API like:
{
"pagination":
{
"results" : 2248,
"page" : 1,
"page_size" : 200,
**"pages" : 12**
},
"products" :
[ {"id": "370c3876-a2b9-11e2-b2b4-bc764e10976c", "source_id": "",....}]}
I would like to retrieve "pages" : 12 from pagination. How can I do it?
I tried this and it worked fine
$data = ' {
"pagination":
{
"results" : 2248,
"page" : 1,
"page_size" : 200,
"pages" : 12
}
}';
$response = json_decode($data, true);
echo $response['pagination']['pages'];//12
Use json_decode to decode the api response, then access the property.
Example:
$response = json_decode($data, true);
echo $response['pagination']['pages'];
<?php
$object = json_decode($your_api_return_string);
$pages = $object->pagination->pages;
echo $pages;
?>

Categories