This question already has answers here:
How to extract and access data from JSON with PHP?
(1 answer)
Accessing JSON object elements in PHP
(1 answer)
Closed 4 years ago.
i have JSON data as bellow and want to print "Page" and "PageCount" using php let me know how can i do that.
{
"response": {
"Page": 1,
"PageCount": 1,
"RecordsSent": 1,
"RecordsFound": 1,
"Stock": [
{
"Colour": "OFF WHITE",
"Size": "S",
"Style": "A0000001",
"Article": "FLORAL 1",
"Size_Range": "S - 3XL",
"In_Stock": 58,
"Demand": 0,
"Supply": 2,
"Sell_Price9": 0
}
]
}
}
how can i print "Page" and "PageCount" only?
You can try this code:
$content = '{
"response": {
"Page": 1,
"PageCount": 1,
"RecordsSent": 1,
"RecordsFound": 1,
"Stock": [
{
"Colour": "OFF WHITE",
"Size": "S",
"Style": "A0000001",
"Article": "FLORAL 1",
"Size_Range": "S - 3XL",
"In_Stock": 58,
"Demand": 0,
"Supply": 2,
"Sell_Price9": 0
}
]
}
}';
$data = json_decode($content, true);
echo "Page:", $data['response']['Page'], "\n";
echo "PageCount:", $data['response']['PageCount'];
json_decode second param is
Assoc - When TRUE, returned objects will be converted into associative arrays.
That means, if assoc = false or not isset, than you have object:
echo "Page:", $data->response->Page, "\n";
echo "PageCount:", $data->response->PageCount;
You can parse it, like this: Live Demo
<?php
$json = '{
"response": {
"Page": 1,
"PageCount": 1,
"RecordsSent": 1,
"RecordsFound": 1,
"Stock": [
{
"Colour": "OFF WHITE",
"Size": "S",
"Style": "A0000001",
"Article": "FLORAL 1",
"Size_Range": "S - 3XL",
"In_Stock": 58,
"Demand": 0,
"Supply": 2,
"Sell_Price9": 0
}
]
}
}';
$decoded_json = json_decode($json);
echo "Page: ".$decoded_json->response->Page."<br/>";
echo "Page Count: ".$decoded_json->response->PageCount;
Related
I have a wordpress endpoint and I have some json data.
Unfortunately I dont know how to return this json data in the function. I tried json_decode but it doesn't return anything. Then endpoint works. If I use json_encode it returns data, but also include linebreaks and stuff. The problem seems to be with the syntax as it is already a complete json what I have. How can I return something that is already in json syntax?
add_action('wp_ajax_nopriv_inboundCall', 'testFunction');
add_action('wp_ajax_inboundCall', 'testFunction');
function testFunction() {
echo json_decode('{
"testData": [
{
"_id": "1",
"name": "testName1"
},
{
"_id": "2",
"name": "testName2"
},
],
"testState": {
"1": [
1,
0
"2": [
1,
0
]
}
}');
die();
}
function testFunction() {
return json_decode('{
"testData": [
{
"_id": "1",
"name": "testName1"
},
{
"_id": "2",
"name": "testName2"
},
],
"testState": {
"1": [
1,
0
"2": [
1,
0
]
}
}'); }
I saved the output of json_decode to a variable and then run json_encode on that variable. Now it seems to work.
function inboundCall() {
$json = json_decode('{
"topics": [
{
"_id": "1",
"name": "davisio",
"crdate": "2022-01-17T12:40:03.430Z",
"modified": "2022-01-17T12:40:03.430Z"
},
{
"_id": "2",
"name": "LoRaWAN",
"crdate": "2022-01-17T12:40:33.848Z",
"modified": "2022-01-17T12:40:33.848Z"
},
{
"_id": "3",
"name": "Kommunale Beziehungen",
"crdate": "2022-01-19T15:17:10.094Z",
"modified": "2022-01-19T15:17:10.094Z"
},
{
"_id": "4",
"name": "Test",
"crdate": "2022-03-31T13:29:41.799Z",
"modified": "2022-03-31T13:29:41.799Z"
}
],
"serviceState": {
"1": [
1,
0,
0,
1,
0,
0,
0,
1
],
"2": [
1,
0,
0,
0,
0,
0,
0,
1
],
"4": [
1,
0,
0,
0,
0,
0,
0,
1
]
}
}');
echo json_encode($json);
die();
}
I want to pull data from below JSON format using PHP (foreach loop).
User detail is correspondence to house detail and house detail correspondence to individual meter reading.
I want to show Username, Device_No and all meter_detail field. Please help me out.
{
"id": 7,
"Username": "user",
"Housename": "Leela",
"Houses_list": [{
"id": 1,
"Device_No": 1111,
"meter_detail": [{
"id": 1,
"flow": 12,
"date": "2020-02-13T12:05:14.709Z",
"opening": 5,
"volume": 1234
},
{
"id": 2,
"flow": 32,
"date": "2020-02-13T12:05:26.821Z",
"opening": 2,
"volume": 1235
}
]
},
{
"id": 2,
"Device_No": 231,
"meter_detail": [{
"id": 3,
"flow": 78,
"date": "2020-02-13T12:05:41.331Z",
"opening": 5,
"volume": 7854
}]
}
]
}
You need to convert the JSON to an array by using json_decode(). Then a couple of foreach loops would do work for you:
<?php
$json = '{
"id": 7,
"Username": "user",
"Housename": "Leela",
"Houses_list": [{
"id": 1,
"Device_No": 1111,
"meter_detail": [{
"id": 1,
"flow": 12,
"date": "2020-02-13T12:05:14.709Z",
"opening": 5,
"volume": 1234
},
{
"id": 2,
"flow": 32,
"date": "2020-02-13T12:05:26.821Z",
"opening": 2,
"volume": 1235
}
]
},
{
"id": 2,
"Device_No": 231,
"meter_detail": [{
"id": 3,
"flow": 78,
"date": "2020-02-13T12:05:41.331Z",
"opening": 5,
"volume": 7854
}]
}
]
}';
$input = json_decode($json, true);
echo 'Username: '.$input['Username'].'<br>';
foreach ($input['Houses_list'] as $device){
echo '<br>Device No: '.$device['Device_No'].'<br>';
foreach ($device['meter_detail'] as $metrics){
echo '<table style="border: 1px solid black">';
foreach ($metrics as $key => $metric){
echo '<tr><td>'.$key.'</td><td>'.$metric.'</td></tr>';
}
echo '</table>';
}
}
?>
Output:
This question already has answers here:
PHP Array to JSON Array using json_encode(); [duplicate]
(4 answers)
Closed 5 years ago.
I tried real hard for my title to make sense haha. I have this JSON:
[{
"0": {
"id": 130427,
"created_at": 1512521776301,
"updated_at": 1512549188911,
"category": 0,
"platform": 6,
"date": 1513987200000,
"region": 8,
"y": 2017,
"m": 12,
"human": "2017-Dec-23",
"game": 76663
},
"2": {
"id": 131795,
"created_at": 1514172411633,
"updated_at": 1514190849639,
"category": 0,
"platform": 39,
"date": 1513987200000,
"region": 8,
"y": 2017,
"m": 12,
"human": "2017-Dec-23",
"game": 78658
}
}]
As you can see the position of the JSON object in the global json serves as the name of the object and I don't want this. This is what I want:
[{
"id": 130427,
"created_at": 1512521776301,
"updated_at": 1512549188911,
"category": 0,
"platform": 6,
"date": 1513987200000,
"region": 8,
"y": 2017,
"m": 12,
"human": "2017-Dec-23",
"game": 76663
},
{
"id": 131795,
"created_at": 1514172411633,
"updated_at": 1514190849639,
"category": 0,
"platform": 39,
"date": 1513987200000,
"region": 8,
"y": 2017,
"m": 12,
"human": "2017-Dec-23",
"game": 78658
}
]
I want the objects without a name. This is the code I'm using:
$json = file_get_contents('./releases.json');
$data = json_decode($json, TRUE);
$region = isset($_GET['region']) ? $_GET['region'] : null;
# if region is not null: ?region=8
if ($region) {
$region_filter = function($v) use ($region) {
// 8 == Worldwide
if ($v['region'] == $region || $v['region'] == 8) {
return true;
} else {
return false;
}
};
$data = array_filter($data['data'], $region_filter);
}
header('Content-Type: application/json');
echo json_encode(array($data)); // good
Thank you
You need to use array_values() to reindex the array.
PHP's json_encode() function will only produce an array if all array keys are numeric and don't have any gaps, e.g. 0, 1, 2, 3 etc. The problem is that array_filter() can remove certain keys and leave gaps, which causes json_encode() to include the keys as you show in your example. You can fix this by using array_values() to re-index the array before calling json_encode().
Here is an example:
<?php
// numeric array keys with no gaps
$a = ['a', 'b', 'c'];
echo json_encode($a);
// ["a","b","c"]
// filter out the 'b' element to introduce a gap in the keys
$a = array_filter($a, function ($v) {
return $v !== 'b';
});
echo json_encode($a);
// {"0":"a","2":"c"}
// re-index the array to remove gaps
$a = array_values($a);
echo json_encode($a);
// ["a","c"]
Thanks in prior for advising. I have the following JSON I retrieve from a REST Service.
"events": [
{
"id": 408,
"name": "My Test1",
"modulename": "test",
"instance": 0,
"timestart": 1470370500,
"timeduration": 864000,
},
{
"id": 418,
"name": "Quiz Open",
"modulename": "quiz",
"instance": 225,
"timestart": 1473737880,
"timeduration": 0,
},
{
"id": 423,
"name": "Quiz Close",
"modulename": "quiz",
"instance": 225,
"timestart": 1476665040,
"timeduration": 0,
},
{
"id": 409,
"name": "August event",
"modulename": "event",
"instance": 0,
"timestart": 1467295200,
"timeduration": 2474700,
}
]
I need to read the JSON and output in the following JSON format
"output": [
{
"name":
"Start":
"End":
}
]
My question comes in the point of the name as "Quiz" which is the "modulename" in the JSON input. The Quiz opens at a date (timestart) with modulename as "quiz" and "instance" - 225 as the unique identifier and ends at a different date ( timestart ) with the same instance id. The json contains 100s of events in one big array. My "End" in output json object is the "timestart" + "timeduration".
My Question is what is the effective algorithm to iterate if the module name is "quiz" get the instance and loop through the whole array to find the next occurence of the instance and add to the output json. Any pointers ?
At first make sure that your json is in right format if your json is like that:-
$str='{"events": [
{
"id": 408,
"name": "My Test1",
"modulename": "test",
"instance": 0,
"timestart": 1470370500,
"timeduration": 864000
},
{
"id": 418,
"name": "Quiz Open",
"modulename": "quiz",
"instance": 225,
"timestart": 1473737880,
"timeduration": 0
},
{
"id": 423,
"name": "Quiz Close",
"modulename": "quiz",
"instance": 225,
"timestart": 1476665040,
"timeduration": 0
},
{
"id": 409,
"name": "August event",
"modulename": "event",
"instance": 0,
"timestart": 1467295200,
"timeduration": 2474700
}
]}';
Then you can do this....`
$arr=json_decode($str,true);
$result=array();
$prevInstance=array();
foreach($arr['events'] as $key=>$val){
if($val['modulename']=='quiz' && array_key_exists($val['instance'], $prevInstance)){
$k= $prevInstance[$val['instance']];
$result['output'][$k]['End']=$val['timestart'];
}else{
$tmp['name']=$val['name'];
$tmp['Start']=$val['timestart'];
$tmp['End']=$val['timeduration'];
$result['output'][$val['id']]=$tmp;
}
$prevInstance[$val['instance']]=$val['id'];;
}
$data=array();
foreach ($result['output'] as $ret){
$data['output'][]=$ret;
}
echo "<pre>";
echo json_encode($data);
$array = json_decode($event,true); // first decode your retrieved array
$output = array();
foreach ($array as $key) { // then loop through it
if ($array[$key]['modulename'] == "quiz") { // only select if modulename is "quiz"
$obj = array("name" => $array[$key]['name'], "Start" => $array[$key]['timestart'], "END" => ($array[$key]['timestart'] + $array[$key]['timeend']));
array_push($output, $obj);
} else {
return;
}
}
return json_encode($output); // in last for output in JSON, encode the output array
//output: [{"name":"quiz","Start":123,"END":579},{"name":"quiz","Start":123,"END":579},{"name":"quiz","Start":123,"END":579}]
I am retrieving the following array, which is the options list for a product, using the bigCommerece API. Using echo $curlProductOptions I see the following echoed to the screen:
[
{
"id": 412,
"option_id": 37,
"display_name": "testSteveMemory",
"sort_order": 0,
"is_required": true
},
{
"id": 413,
"option_id": 34,
"display_name": "Hard Drive (desktop)",
"sort_order": 1,
"is_required": true
},
{
"id": 414,
"option_id": 24,
"display_name": "Include Keyboard & Mouse",
"sort_order": 2,
"is_required": true
},
{
"id": 415,
"option_id": 33,
"display_name": "Memory",
"sort_order": 3,
"is_required": true
}
]
So I am presuming I have an array within $curlProductOptions containing the above data.
I now need to loop through each element and echo each 'option_id'.
I have tried :
foreach($curlProductOptions['option_id'] as $value)
{echo $value;}
and:
for ($i = 0; $i < count($curlProductOptions); ++$i)
{echo 'optionID ='.$curlProductOptions[$i].option_id.'<br>';}
I also tried just to echo one of the elements.
echo $curlProductOptions['option_id'][0];
echo $curlProductOptions[0]['option_id'];
What am I not understanding here?
You have json encoded string. So you need to json_decode first .
try like this:
$curlProductOptions = json_decode($curlProductOptions,true);//create associative array
foreach($curlProductOptions['option_id'] as $value){
echo $value;
}
This works fine for me:
$curlProductOptions = json_decode($curlProductOptions, true);
foreach($curlProductOptions as $value){
echo $value['option_id'];
}