Adding JSON stored in database to JSON string - php

I have some JSON stored in a database. Please assume I have a good reason for doing so. I then retrieved it from the DB and wish to include it in another JSON string. The following treats the JSON from the DB as standard strings instead of JSON as I desire. Will I need to loop over $json_from_db and first convert the cmd values to arrays/objects, or is there a better way?
<?php
$json_from_db=array(
array('id'=>1,'cmd'=>'{"a":{}}'),
array('id'=>3,'cmd'=>'{"b":{"name":"x","value":"xxx"}}'),
array('id'=>5,'cmd'=>'{"b":{"name":"y","value":"yyy"}}'),
array('id'=>9,'cmd'=>'{"c":{"name":"z","extra":"hello","more"=>1}}'),
);
$arr=array('a'=>"hello",'json'=>array('a'=>"hello"),'json_from_db'=>$json_from_db);
$json=json_encode($arr);
echo($json."\n\n");
print_r(json_decode($json));
OUTPUT
{"a":"hello","json":{"a":"hello"},"json_from_db":[{"id":1,"cmd":"\"a\":{}"},{"id":3,"cmd":"\"b\":{\"name\":\"x\",\"value\":\"xxx\"}"},{"id":5,"cmd":"\"b\":{\"name\":\"y\",\"value\":\"yyy\"}"},{"id":9,"cmd":"\"c\":{\"name\":\"z\",\"extra\":\"hello\",\"more\"=>1}"}]}
stdClass Object
(
[a] => hello
[json] => stdClass Object
(
[a] => hello
)
[json_from_db] => Array
(
[0] => stdClass Object
(
[id] => 1
[cmd] => "a":{}
)
[1] => stdClass Object
(
[id] => 3
[cmd] => "b":{"name":"x","value":"xxx"}
)
[2] => stdClass Object
(
[id] => 5
[cmd] => "b":{"name":"y","value":"yyy"}
)
[3] => stdClass Object
(
[id] => 9
[cmd] => "c":{"name":"z","extra":"hello","more"=>1}
)
)
)

Note that "b":{"name":"x","value":"xxx"} isn't valid json.
You need to decode all cmd's json-string from $json_from_db,
array_walk_recursive($json_from_db, function (&$item, $key) {
if ($key === 'cmd') {
$item = json_decode($item, true);
}
});
Then you can do
$arr = array(
'a' => "hello",
'json' => array('a'=>"hello"),
'json_from_db' => $json_from_db
);
$json = json_encode($arr);
Demo.

Related

Search in multidimensional Stdclass PHP

I want to search in PHP within a specific object. For instance [module] => play in a StdClass object, how can I search for values within the class itself?
Below you can find the whole array:
[flow] => stdClass Object
(
[data] => stdClass Object
(
[action] => start
)
[module] => record_call
[children] => stdClass Object
(
[_] => stdClass Object
(
[data] => stdClass Object
(
[id] => 7696364e90822fdcba4feee30574a7e2
[endless_playback] =>
[terminators] => Array
(
[0] => 1
)
)
[module] => play
[children] => stdClass Object
(
[_] => stdClass Object
….
I want to get the output like:
[data] => stdClass Object
(
[id] => 7696364e90822fdcba4feee30574a7e2
[endless_playback] =>
[terminators] => Array
(
[0] => 1
)
)
[module] => play
[children] => stdClass Object
(
[_] => stdClass Object
….
Can someone help me with that? Thank you in advance!
You have a couple of simpler options here.
The first is if you're receiving this data via a json_decode() call, add true as a second parameter:
$decoded = json_decode($data, true);
The second is to convert this to a simple associative array structure by taking advantage of the above and the use of json_encode():
$decoded = json_decode(json_encode($data), true);
With your simple array structure, it's now possible to recursively traverse the array to find the matching key/value pair desired:
function findModule($data, $module_name) {
if(!is_array($data)) return null;
if(array_key_exists('module', $data)) {
if($data['module'] === $module_name) {
return $data;
}
}
foreach($data as $key=>$val) {
$result = findModule($val, $module_name);
if(!is_null($result)) {
return $result;
}
}
return null;
}
// Will either return the array of array('data'=>..., 'module'=>'play', 'children': ...) or null if no matching module found.
$module = findModule($decoded, 'play');

Parse JSON from file using PHP from objects/arrays

I get the following output using print_r in php of my decoded JSON:
stdClass Object
(
[assignments] => Array
(
[0] => stdClass Object
(
[assignmentid] => 1
[grades] => Array
(
[0] => stdClass Object
(
[id] => 1
[userid] => 3
[attemptnumber] => 0
[timecreated] => 1484244192
[timemodified] => 1484244203
[grader] => 2
[grade] => 85.00000
)
)
)
)
[warnings] => Array
(
)
)
I want to get the value for [grade] => 85.00000 and store it in a variable. How would I go about doing this?
What about:
$var = $obj->assignments[0]->grades[0]->grade;
Use true as second parameter of json_decode() to decode it to array and then you have to loop over your result.
$data = json_decode($json, true);
foreach ($data['assignments'] as $row) {
foreach ($row['grades'] as $grade) {
echo $grade['grade'];
}
}

How to check array object and array?

First array:
[VariationSpecificsSet] => SimpleXMLElement Object
(
[NameValueList] => Array
(
[0] => SimpleXMLElement Object
(
[Name] => Size
[Value] => Array
(
[0] => 5FT King Size
[1] => 4FT6 Double
)
)
[1] => SimpleXMLElement Object
(
[Name] => Main Colour
[Value] => Array
(
[0] => Brown
[1] => Black
)
)
)
)
Second Array:
[Variation] => SimpleXMLElement Object
(
[StartPrice] => 14.99
[Quantity] => 12
[VariationSpecifics] => SimpleXMLElement Object
(
[NameValueList] => SimpleXMLElement Object
(
[Name] => Size
[Value] => No.10-1M
)
)
)
examine above two arrays
i want to store value NameValueList in database but the problem is sometimes it is SimpleXMLElement Object and sometimes it is Array
how can i store them ...??
You can detect is by is_array().
$myVal=$test['NameValueList'];
if(is_array($myVal) && count($myVal)>0){
foreach($myVal as $item){
echo $item->Name.":".echo $item->Value;
}
} else {
echo $myVal->Name.":".echo $myVal->Value;
}
Did you tried using json_encode like below.
You can convert the object to array.
$array=json_decode(json_encode($object),true);

Merge arrays in an object

Im new to php and json. can you please suggest me on how to get the my desired output.
JSON File:
{
"1415772360":[
{"apple":"0"},
{"mango":"0"},
{"grapefruit":"0"},
{"melons":"12"},
{"peaches":"2"},
{"banana":"1"}
],
"1415772420":[
{"apple":"0"},
{"mango":"0"},
{"grapefruit":"0"},
{"melons":"7"},
{"peaches":"1"},
{"banana":"1"}
]
}
Desired Output
[
{
"minute":"1415772360",
"apple":"0",
"mango":"0",
"grapefruit":"0",
"melons":"12",
"peaches":"2",
"banana":"1”
},
{
"minute":"1415772420",
"apple:"0",
"mango":"0",
"grapefruit":"0",
"melons":"7",
"peaches":"1",
"banana":"1”
}
]
How can I do this in PHP?
I really appreciate your help. Thanks.
I would give json_decode a try. It won't get your desired output, but it will create an array from your JSON.
Documentation: http://php.net/manual/en/function.json-decode.php
My test:
$json = "{\"1415772360\":[{\"apple\":\"0\"},{\"mango\":\"0\"},{\"grapefruit\":\"0\"},
{\"melons\":\"12\"},{\"peaches\":\"2\"},{\"banana\":\"1\"}], \"1415772420\":
[{\"apple\":\"0\"},{\"mango\":\"0\"},{\"grapefruit\":\"0\"},{\"melons\":\"7\"},
{\"peaches\":\"1\"},{\"banana\":\"1\"}]}";
$new = json_decode($json);
print_r($new);
Output:
stdClass Object ( [1415772360] => Array ( [0] => stdClass Object ( [apple] => 0 )
[1] => stdClass Object ( [mango] => 0 ) [2] => stdClass Object ( [grapefruit] => 0 )
[3] => stdClass Object ( [melons] => 12 ) [4] => stdClass Object ( [peaches] => 2 )
[5] => stdClass Object ( [banana] => 1 ) ) [1415772420] => Array ( [0] => stdClass Object ( [apple] => 0 )
[1] => stdClass Object ( [mango] => 0 ) [2] => stdClass Object ( [grapefruit] => 0 )
[3] => stdClass Object ( [melons] => 7 ) [4] => stdClass Object ( [peaches] => 1 )
[5] => stdClass Object ( [banana] => 1 ) ) )
tyteen4a03 is correct that this just requires some looping to re-write the structure. This would be done as follows:
// Original JSON string
$json = '{
"1415772360":[
{"apple":"0"},
{"mango":"0"},
{"grapefruit":"0"},
{"melons":"12"},
{"peaches":"2"},
{"banana":"1"}
],
"1415772420":[
{"apple":"0"},
{"mango":"0"},
{"grapefruit":"0"},
{"melons":"7"},
{"peaches":"1"},
{"banana":"1"}
]
}';
// Convert JSON to array
$content = json_decode($json);
// Create new array container
$crate = array();
// Get minutes
foreach ($content AS $minute => $fruitbasket) {
$tmp = new stdClass;
$tmp->minutes = $minute;
// Get array of objects
foreach ($fruitbasket AS $fruits)
{
// Get object element and value
foreach ($fruits AS $key => $value)
{
// add to temporary object
$tmp->$key = $value;
}
}
// write to new array
$crate[] = $tmp;
}
print(json_encode($crate));

Getting an objects property with slashes in it

I'm getting a json result back from an api request to the freebase database.
This is part of the object returned called $json. A var dump of $json:
stdClass Object
(
[name] => Abomey
[/location/statistical_region/population_growth_rate] =>
[/common/topic/article] => Array
(
[0] => stdClass Object
(
[id] => /m/0jk2c
)
)
How can I subtract the /m/0jk2c part?
$json->/common/topic/article[0]->id (obviously) doesn't work.
This should do it:
$json->{"/common/topic/article"}[0]->id
This is what you should use
$class->{'/location/statistical_region/population_growth_rate'}['/common/topic/article'][0]->id
Reason your Object looks like this
$std = new stdClass();
$std->id = '/m/0jk2c' ;
$json = new stdClass();
$json->name = "Abomey" ;
$json->{'/location/statistical_region/population_growth_rate'} = array('/common/topic/article'=>array($std));
If you run
var_dump($json->{'/location/statistical_region/population_growth_rate'}['/common/topic/article'][0]->id);
Output
string '/m/0jk2c' (length=8)
Run
echo "<pre>";
print_r($json);
Output
stdClass Object
(
[name] => Abomey
[/location/statistical_region/population_growth_rate] => Array
(
[/common/topic/article] => Array
(
[0] => stdClass Object
(
[id] => /m/0jk2c
)
)
)
)

Categories