Decode json string 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.
I would like to get the values for 'datelog_collected' and 'value' fields:
{
"data": [
{
"datelog_collected": "2016-09-01 13:57:13",
"value": "36.06"
}
]
}
So far, i tried with json_decode but without success. I want this to stay as an object. Thanks

If you use
$object = json_decode($your_JSON_string);
datelog_collected and value will not be properties of the resulting $object.
The object will have only one property, data. data is a numerically indexed array (that is what the square brackets in the JSON mean) which contains one object. The properties you want belong to that object.
So you can get what you want with $object->data[0]->datelog_collected, etc.

If you use json_decode as:
$res=json_decode('{ "data": [ { "datelog_collected": "2016-09-01 13:57:13", "value": "36.06" } ] }');
$res would be an object so you can access: $res->data
And if you add second parameter true (json as array)
$res=json_decode('{ "data": [ { "datelog_collected": "2016-09-01 13:57:13", "value": "36.06" } ] }', true);
$res would be an array so you can access: $res["data"]

Try this
<?php
$datelog_collected=array();
$datelog_value=array();
$data='{ "data": [ { "datelog_collected": "2016-09-01 13:57:13", "value": "36.06" } ] }';
$data_array=json_decode($data,true);//true create array if you want object then remove true
if(is_array($data_array)&&!empty($data_array))
{
foreach ($data_array as $key => $value) {
if(is_array($value))
{
foreach ($value as $key1 => $value1) {
foreach ($value1 as $key2 => $value2) {
if($key2=="datelog_collected")
{
$datelog_collected[]=$value2;
}else{
$datelog_value[]=$value2;
}
}
}
}
}
//here is datelog_collected
var_dump($datelog_collected);
echo "<br/>-----------------------<br/>";
//here is datelog_value
var_dump($datelog_value);
}
?>
check working link http://main.xfiddle.com/7ffb488b/json_decoder.php

Related

how to search in Json and get sub data [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 3 years ago.
i have a json file of users with all descriptions and its hard to find them with data[2]. imagine in data[0]->users->data i have 3 user and i want to find name = "Stafin" to get description->data->instagram and get value. i'll give you a simple json data
{"data":[
{
"id":1,
"category_name":"Writers",
"users":{
"data":[{
"name":"Steve",
"id":"1",
"description":{
"data":[
{
"instagram":"steveid"
}
]
}
},{
"name":"Stafin",
"id":"2",
"description":{
"data":[
{
"instagram":"stafinid"
}
]
}
},{
"name":"Sara",
"id":"3",
"description":{
"data":[
{
"instagram":"saraid"
}
]
}
}]
}
}
]}
Code:
<?php
$str = file_get_contents('http://localhost/json/test.json');
$json = json_decode($str, true);
function searchForId($id, $array) {
foreach ($array as $key => $val) {
if ($val['id'] === $id) {
return $key;
}
}
return null;
}
$id = searchForId('2', $json);
echo $id;
?>
note that: answer it in php language
sorry for my bad English language. if you didn't get that, just tell me to describe more
Your function searches for id, but you said you wanted to search for name. You can make the key another parameter of the function. Then you can use it to find the id in the data array, and the name in the users['data'] array.
function searchArray($searchkey, $searchval, $array) {
foreach ($array as $key => $val) {
if ($val[$searchkey] === $searchval) {
return $val;
}
}
return null;
}
foreach ($json['data'] as $data) {
$user = searchArray('name', 'Stafin', $data['users']['data']);
if ($user) {
echo "Found Stafin";
foreach ($user['description']['data'] as $desc) {
if (isset($desc['instagram'])) {
echo ", Instagram is {$desc['instagram']}";
break;
}
}
break;
}
}

How to find json direct parent based on children value

I need to find the direct parent of all instance of "type": "featured-product" in a JSON file using PHP. store this parent string in a variable. use a foreach.
In the example below, the variable would have the value "1561093167965" and "3465786822452"
I'm a little lost, thank you for the help!
{
"current": {
"sections": {
"1561093167965": {
"type": "featured-product"
},
"3465786822452": {
"type": "featured-product"
}
}
}
}
foreach ($json['current']['sections'] as $sectionName => $section) {
if ($section['type'] && $section['type'] == 'featured-product') {
$featuredId = $sectionName;
}
}
Another approach you can take is to create a new array containing only featured-products using array_filter and then extract the keys. From the docs:
If the callback function returns TRUE, the current value from array is
returned into the result array. Array keys are preserved.
$product_sections = array_keys(
array_filter($json['current']['sections'], function($val) {
return $val['type'] === 'featured-product';
}));
Demo
The problem in your original code is that your $featuredId variable is getting overwritten in each iteration of the loop, so when it ends its value will be the one of last element processed. If you have to deal with multiple values, you'll have to add it to an array or do the work directly inside the foreach. You can see the other answers for how to fix your code.
There is probably a cleaner way but this works using json_decode and iterating over the array with foreach
$json='{
"current": {
"sections": {
"1561093167965": {
"type": "featured-product"
},
"3465786822452": {
"type": "featured-product"
}
}
}
}';
$e=json_decode($json,true);
foreach($e['current']['sections'] as $id=>$a){
if($a['type']=='featured-product'){
echo 'the parent id is '.$id;
}
}
//change this with the real json
$json='{
"current": {
"sections": {
"1561093167965": {
"type": "featured-product"
},
"3465786822452": {
"type": "featured-product"
}
}
}
}';
$result = [];
$jsond=json_decode($json,true);
foreach($jsond['current']['sections'] as $k=>$v){
if($v['type']=='featured-product'){
$result[] = $k;
}
}

How to filter and restructure json data with php?

I couldn't find an answer, so I decided to ask.
I get this response from an API:
[
{
"seasonNumber":1,
"numWins":1,
"numHighBracket":2,
"numLowBracket":2,
"seasonXp":111,
"seasonLevel":5,
"bookXp":0,
"bookLevel":1,
"purchasedVIP":false
},
{
"seasonNumber":2,
"numWins":1,
"numHighBracket":21,
"numLowBracket":31,
"seasonXp":1651,
"seasonLevel":25,
"bookXp":9,
"bookLevel":11,
"purchasedVIP":false
},
{
"seasonNumber":3,
"numWins":9,
"numHighBracket":57,
"numLowBracket":127,
"seasonXp":4659,
"seasonLevel":68,
"bookXp":0,
"bookLevel":100,
"purchasedVIP":true
},
{
"seasonNumber":4,
"numWins":8,
"numHighBracket":19,
"numLowBracket":36,
"seasonXp":274,
"seasonLevel":33,
"bookXp":7,
"bookLevel":35,
"purchasedVIP":true
}
]
I am trying to change the json data to this:
{
"seasons":
[
{
"season":1,
"battle_pass":false
},
{
"season":2,
"battle_pass":false
},
{
"season":3,
"battle_pass":true
},
{
"season":4,
"battle_pass":true
}
]
}
In my current code I am using regex like this:
preg_match_all("/(?:\{\"seasonNumber\"\:(\w)|purchasedVIP\"\:(\w+))/", $response, $seasons);
echo '{"seasons":'.json_encode($seasons, JSON_FORCE_OBJECT, JSON_PRETTY_PRINT).'}';
It's basically putting everything in a separate array but that's not what I want.
Decode the json, restructure the data, re-encode.
Code: (Demo)
// your $json =
foreach (json_decode($json) as $set) {
$array[] = ["season" => $set->seasonNumber, "battle_pass" => $set->purchasedVIP];
}
echo json_encode(["seasons" => $array]);
Output:
{"seasons":[{"season":1,"battle_pass":false},{"season":2,"battle_pass":false},{"season":3,"battle_pass":true},{"season":4,"battle_pass":true}]}
p.s. if you want to force objects and pretty print, separate those flags with a pipe (|). https://3v4l.org/qsPb0

Loop json object as array in PHP

How can i loop the response to get all ids and names?
If the response like this:
{
"Data": [
{
"Id": "4321",
"Name": "Dog"
},
{
"Id": "749869",
"Name": "Cat"
}
]
}
I can get all the ids and names using this code:
foreach (json_decode($response->content)->Data as $resp) {
echo $resp->Id;
echo $resp->Name;
}
But, if the response like this:
{
"Data": {
"dog": {
"Id": "4321",
"Name": "Dog"
},
"cat": {
"Id": "749869",
"Name": "Cat"
}
}
}
How can i get all the ids and names without knowing the amount of the array? Thank you.
You can get PHP to read everything into an (associative where applicable) array.
foreach (json_decode($response->content, true)["Data"] as $resp) { //2nd parameter is to decode as array
echo $resp["Id"];
echo $resp["Name"];
}
Example run: https://eval.in/954621
Alternatively you can do the lazy thing and just cast:
foreach ((array)json_decode($response->content)->Data as $resp) {
echo $resp->Id;
echo $resp->Name;
}
Well if you want to extract all ids into one array (I assume you mean all into one array), to use in a database query as an example. I would recommend you doing like this.
$ids = array_values(array_map(function($animal){
return intval($animal['Id']);
}, json_decode($response->content, true)['Data']));
var_dump($ids);
you do the same ! foreach loop would work on both.
the json response supposed to have the same format every time, unless you have a really weird API.
<?php
$response = json_decode($json);
foreach($response as $animal => $data)
{
echo $animal;
echo $data->id;
echo $data->name;
}

How to get json format for monogo db object [duplicate]

I am using PHP to connect with MongoDB. My code is as follows.
// connect
$m = new MongoClient($con_string); // connect to a remote host at a given port
$db = $m->main;
$customers = $db->customer->find();
i want to return $customers collection as json document to my HTML. How can i do this?
You can do this two ways:
echo json_encode(iterator_to_array($customers));
or you can manually scroll through it:
foreach($customers as $k => $row){
echo json_encode($row);
}
Each of MongoDBs objects should have their __toString() methods correctly implemented to bring back the representation of the value.
This also will work. And you can customize your json as well.
$arr = array();
foreach($customers as $c)
{
$temp = array("name" => $c["name"], "phone" => $c["phone"],
"address" => $c["address"]);
array_push($arr, $temp);
}
echo json_encode($arr);
Other answers work, but it is good to know that the generated JSON will have the following form (in this example I use an hypothetical "name" field for your customers):
{
"5587d2c3cd8348455b26feab": {
"_id": {
"$id": "5587d2c3cd8348455b26feab"
},
"name": "Robert"
},
"5587d2c3cd8348455b26feac": {
"_id": {
"$id": "5587d2c3cd8348455b26feac"
},
"name": "John"
}
}
So in case you don't want the Object _id to be the key of each of your result objects you can add a false parameter to iterator_to_array.
Your code would be:
echo json_encode(iterator_to_array($customers, false), true);
This creates the same result as
$result = Array();
foreach ($customers as $entry) {
array_push($result, $entry);
}
echo json_encode($result, true);
which is an array of JSON objects
[
{
"_id": {
"$id": "5587d2c3cd8348455b26feab"
},
"name": "Robert"
},
{
"_id": {
"$id": "5587d2c3cd8348455b26feac"
},
"name": "John"
}
]

Categories