Here i have one array(first array) inside i have one more array(second array), now i want to display only first image from second array(galleryImages) , how can do this. i tried but i am not able to get the results
print_r($response);
Array
(
[0] => stdClass Object
(
[gallery_id] => 2
[title] => Annual Day 2017
[description] =>
[galleryImages] => ["1.jpg","2.jpg","3.jpg","4.jpg"]
[reg_on] => 2017-05-17 01:55:12
[created_by] => rajeshdash123#gmail.com
[school_id] => 2
[status] => 0
)
[1] => stdClass Object
(
[gallery_id] => 3
[title] => Sports Day
[description] =>
[galleryImages] => ["1.jpg","2.jpg","3.jpg"]
[reg_on] => 2017-05-17 01:55:36
[created_by] => rajeshdash123#gmail.com
[school_id] => 2
[status] => 0
)
)
Expected Results
{
"status": "Success",
"data": [
{
"gallery_id": "2",
"title": "Annual Day 2017",
"description": "",
"galleryImagesCount": 4,
"gallery":"1.jpg"
},
{
"gallery_id": "3",
"title": "Sports Day 2017",
"description": "",
"galleryImagesCount": 4,
"gallery":"1.jpg"
}
],
}
I tried like this but is i am not getting the exact results
$images = array();
foreach ($response as $key => $value)
{
$img['gallery_id'] = $value->gallery_id;
$img['title'] = $value->title;
$img['description'] = $value->description;
$img['galleryImagesCount'] = count(json_decode($value->galleryImages,true));
$img['gallery'] = json_decode($value->galleryImages,true);
array_push($images,$img);
}
$return=array('status'=>"Success",'Images'=>$images);
echo json_encode($return);
Getting Results
{
"status": "Success",
"Images": [
{
"gallery_id": "2",
"title": "Annual Day 2017",
"description": "",
"galleryImagesCount": 4,
"gallery": [
"d17ac9d0aeb6435eaa294e0d69d4cc8f.jpg",
"a91945e0cf55379f51cf5faef10d7a4a.jpg",
"2d1501045ddbb3ccc238e70f9af05027.jpg",
"071c3b5f969bed1d1e2ee4b6531e4444.jpg"
]
},
{
"gallery_id": "3",
"title": "Sports Day",
"description": "",
"galleryImagesCount": 4,
"gallery": [
"f0ba574fd46a01ff5a41855a97c710ca.jpg",
"1d10802f1b74e660117f36bd6dd0aa26.jpg",
"e705fb66f767a1b914200ca8d3cae700.jpg",
"3d5d8828331e13d3decc94021a64e5ca.jpg"
]
}
]
}
Here what happening means gallery is coming an array , for me don't want array i need first image only, please check my expected results, update the answer
Updated expected results
{
"status": "Success",
"Images": [
{
"gallery_id": "2",
"title": "Annual Day 2017",
"description": "",
"galleryImagesCount": 4,
"gallery": [
{
"galleryimage": "1.jpg"
},
{
"galleryimage": "2.jpg"
}
]
},
{
"gallery_id": "3",
"title": "Sports Day",
"description": "",
"galleryImagesCount": 4,
"gallery": [
{
"galleryimage": "1.jpg"
},
{
"galleryimage": "2.jpg"
}
]
}
]
}
Instead of [galleryImages] => ["1.jpg","2.jpg","3.jpg"], use for loop to iterate through galleryImages.
Create an associative array with key =>value pair like [galleryImages] => ["galleryimage1" => "1.jpg", "galleryimage2" => "2.jpg", "galleryimage3" => "3.jpg"].
While json_decode you will get intended output.
My changes and explanations are in the code block:
Code: (Demo)
// assumed that previous line was something like $response=json_decode($json);
$response=[
(object)[
'gallery_id'=>2,
'title'=>'Annual Day 2017',
'description'=>'',
'galleryImages'=>["1.jpg","2.jpg","3.jpg","4.jpg"],
'reg_on'=>'2017-05-17 01:55:12',
'created_by'=>'rajeshdash123#gmail.com',
'school_id'=>2,
'status'=>0
],
(object)[
'gallery_id'=>3,
'title'=>'Sports Day',
'description'=>'',
'galleryImages'=>["1.jpg","2.jpg","3.jpg"],
'reg_on'=>'2017-05-17 01:55:36',
'created_by'=>'rajeshdash123#gmail.com',
'school_id'=>2,
'status'=>0
]
];
foreach ($response as $value){ // removed $key=> because it was unnecessary
$img['gallery_id'] = $value->gallery_id;
$img['title'] = $value->title;
$img['description'] = $value->description;
$img['galleryImagesCount'] = count($value->galleryImages); // removed json_decode()
$img['gallery'] = $value->galleryImages[0]; // removed json_decode and added [0] to access first
$images[]=$img; // swapped push() call with identical function-less "push"
}
if(isset($images)){ // added this condition to ensure there was something to return
$return=array('status'=>"Success",'Images'=>$images);
//var_export($return);
echo json_encode($return);
}else{
// enter some sort of error message / default behavior
}
Output:
{"status":"Success","Images":[{"gallery_id":2,"title":"Annual Day 2017","description":"","galleryImagesCount":4,"gallery":"1.jpg"},{"gallery_id":3,"title":"Sports Day","description":"","galleryImagesCount":3,"gallery":"1.jpg"}]}
Related
In the JSON file, there are multiple item based on the same product_id. I have to create multidimensional array based on product_id and items.
As per my sample php code, product_id is repeatedly listing. Results are printed in php code.
Expecting results are given below.
testData.json
"data": [
{
"product_id": "123456",
"item": "ZAD",
"time": "15:30",
"quantity": 1
},
{
"product_id": "24534"
"item": "REST"
"time": "5:30"
"quantity": 1
},
{
"product_id": "123456"
"item": "RAD"
"time": "10:30"
"quantity": 2
}
]
test.php
$json = file_get_contents('testData.json');
$d_data = json_decode($json, true);
$f_data = $d_data['data'];
foreach($f_data as $data) {
$result = [
$data['product_id'],
$data['item']
]
print_r($result);
/* Array(
[0] => 123456
[1] => ZAD
)
Array(
[0] => 123456
[1] => RAD
)
Array(
[0] => 24534
[1] => REST
)
*/
}
Expecting Result
123456
[
ZAD
[
"time" => "15:30",
"quantity" => 1
],
RAD
[
"time" => "10:30"
"quantity" => 2
],
],
24534
[
REST
[
"time" => "5:30"
"quantity" => 1
]
]
You just need to account for both product_id and item as sub-keys in the final array:
$result = [];
foreach($f_data as $data) {
$result[$data['product_id']][$data['item']] = [
$data['time'],
$data['quantity']
];
}
print_r($result);
Demo: https://3v4l.org/sf7om
I should note, if two items have the same product_id and same item, this code will only keep the last one. If that scenario applies to you, you just need to use the append mode ([]) of the array:
$result[$data['product_id']][$data['item']][] = [
$data['time'],
$data['quantity']
];
I just learned php
I have a separate database table, and I want to combine that table with only 1 parameter with JSON output, but the resulting output is wrong, how to change my JSON to json which is correct and easy to use.
thanks
json output :
[
[
{
"id_service": "3",
"reference_number": "",
"tracking_number": "RJC-0000-0001",
"kd_inbound": "INB-1000-0001",
"tgl_inbound": "2019-11-07 00:00:00",
"status_inb": "1"
}
],
[
{
"id_service": "3",
"reference_number": "",
"kd_outbag": "BAG-1468-0002",
"tanggal_outbag": "2019-11-07 00:00:00",
"status_outbag": "1"
}
],
[
{
"id_service": "3",
"reference_number": "",
"kd_outbound": "OTB-1826-0001",
"tgl_outbound": "2019-11-07 17:04:49",
"status_otb": "1"
}
],
]
this my code
public function awb_get() {
$id = $this->get('tracking_number');
$res= array(
$this->M_tarif->tampil_status_inbound($id),
$this->M_tarif->tampil_status_otboundbag($id),
$this->M_tarif->tampil_status_otboundori($id),
$this->M_tarif->tampil_status_indes($id),
$this->M_tarif->tampil_status_outdes($id),
$this->M_tarif->tampil_status_runsheet($id),
$this->M_tarif->tampil_db_service_status($id)
);
$this->response($res, 200);
}
i want in like this
{
"status": 200,
"error": false,
"awb": [
{
"tracking_number": "RJC-0000-0004",
"status": "order",
"tanggal": "2019-10-30"
},
{
"tracking_number": "RJC-0000-0004",
"status": "Inbound to origin",
"tanggal": "2019-11-03"
}
]
}
Your json response is not correct.
So, first you have to reset your JSON before send to function. I was make sample to rearrange JSON and convert it in stdClass Object. Please check below code to convert with your response.
$arr ='[
[
{
"id_service": "3",
"reference_number": "",
"tracking_number": "RJC-0000-0001",
"kd_inbound": "INB-1000-0001",
"tgl_inbound": "2019-11-07 00:00:00",
"status_inb": "1"
}
],
[
{
"id_service": "3",
"reference_number": "",
"kd_outbag": "BAG-1468-0002",
"tanggal_outbag": "2019-11-07 00:00:00",
"status_outbag": "1"
}
],
[
{
"id_service": "3",
"reference_number": "",
"kd_outbound": "OTB-1826-0001",
"tgl_outbound": "2019-11-07 17:04:49",
"status_otb": "1"
}
],
]';
$result = str_replace(array('[',']','\n'), '',htmlspecialchars(json_encode($arr), ENT_NOQUOTES));
$str = preg_replace('/\\\"/',"\"", $result);
$json = '[';
$json .= substr($str, 2,-1); // Substring -1 character from the end of the json variable, this will be the trailing comma.
$json .= ']';
$jsonData = preg_replace("/,(?!.*,)/", "", $json);
echo "<pre>";
print_r(json_decode($jsonData));
echo "</pre>";
output:
Array
(
[0] => stdClass Object
(
[id_service] => 3
[reference_number] =>
[tracking_number] => RJC-0000-0001
[kd_inbound] => INB-1000-0001
[tgl_inbound] => 2019-11-07 00:00:00
[status_inb] => 1
)
[1] => stdClass Object
(
[id_service] => 3
[reference_number] =>
[kd_outbag] => BAG-1468-0002
[tanggal_outbag] => 2019-11-07 00:00:00
[status_outbag] => 1
)
[2] => stdClass Object
(
[id_service] => 3
[reference_number] =>
[kd_outbound] => OTB-1826-0001
[tgl_outbound] => 2019-11-07 17:04:49
[status_otb] => 1
)
)
This is the data inside a variable named $data and i printed it using print_r().
Array
(
[user_id] => 6
[car_id] => 9
[pickup_name] => only me
[snooze] => 15
[pickup_loc] => pickup location
[drop_loc] => drop location
[note] => see you soon
[schedule] => [ {
"id": "1",
"car_name": "Mercedes-Benz C-Class",
"price": "200",
"status": "0",
"cr_dt": "2019-07-25 18:29:42",
"up_dt": "2019-07-26 11:20:36"
},
{
"id": "2",
"car_name": "Mercedes-Benz C-Class",
"price": "300",
"status": "0",
"cr_dt": "2019-07-25 18:29:42",
"up_dt": "2019-07-26 11:20:36"
} ]
[id] => 16
)
I want to access the data inside ['schedule'] in my foreach loop.
Thanks in advance.
You can use json_decode( $data['schedule]) directly. Otherwise you can use a variable like:
$jsarray = json_decode( $data['schedule])
Then you can access the data.
I am using sports-radar API to get the schedule of NFL week 1. The API returns the following data in json format (I shortened string for example).
"id": "8e45fe2d-fb95-4504-845d-7c815623ccd6",
"year": 2018,
"type": "REG",
"name": "REG",
"week": {
"id": "37435167-5cf6-4cce-b405-ff0e264ced9c",
"sequence": 1,
"title": "1",
"games": [{
"id": "0822b924-eadc-4398-bfe6-83cbbf3a2912",
"status": "scheduled",
"reference": "57570",
"number": 4,
"scheduled": "2018-09-09T17:00:00+00:00",
"entry_mode": "INGEST",
"venue": {
"id": "6ed18563-53e0-46c2-a91d-12d73a16456d",
"name": "Lucas Oil Stadium",
"city": "Indianapolis",
"state": "IN",
"country": "USA",
"zip": "46225",
"address": "500 South Capitol Avenue",
"capacity": 67000,
"surface": "artificial",
"roof_type": "retractable_dome"
},
"home": {
"id": "82cf9565-6eb9-4f01-bdbd-5aa0d472fcd9",
"name": "Indianapolis Colts",
"alias": "IND",
"game_number": 1
},
"away": {
"id": "ad4ae08f-d808-42d5-a1e6-e9bc4e34d123",
"name": "Cincinnati Bengals",
"alias": "CIN",
"game_number": 1
},
"broadcast": {
"network": "CBS"
}
}, {
"id": "0a456149-c547-4856-9b1b-86e1d93887ae",
"status": "scheduled",
"reference": "57574",
"number": 8,
"scheduled": "2018-09-09T17:00:00+00:00",
"entry_mode": "INGEST",
"venue": {
"id": "3c85d89a-ec66-4983-acd5-1381d6c8673a",
"name": "Mercedes-Benz Superdome",
"city": "New Orleans",
"state": "LA",
"country": "USA",
"zip": "70112",
"address": "1500 Sugar Bowl Drive",
"capacity": 73208,
"surface": "artificial",
"roof_type": "dome"
},
"home": {
"id": "0d855753-ea21-4953-89f9-0e20aff9eb73",
"name": "New Orleans Saints",
"alias": "NO",
"game_number": 1
},
"away": {
"id": "4254d319-1bc7-4f81-b4ab-b5e6f3402b69",
"name": "Tampa Bay Buccaneers",
"alias": "TB",
"game_number": 1
},
"broadcast": {
"network": "FOX"
I used the following website as a tutorial on how to display only the the data I need and how to loop over it
Note the JSON string is stored in the variable $schedule
MY Code
// JSON string
$jsonData = $schedule; //get json string
// Convert JSON string to Array
$jsonArray = json_decode($jsonData, true);
// Convert JSON string to Object
$jsonObject = json_decode($schedule);
Looping through PHP Array or Object
$someArray = $jsonArray
foreach ($someArray as $key => $value) {
echo $value["home"] . ", " . $value["away"] . "<br>";
}
// Loop through Object
$someObject = jsonObject
foreach($someObject as $key => $value) {
echo $value->home . ", " . $value->away . "<br>";
}
My ERRORS
When trying to convert the string to an array and attempting to get the away team name I get the error Illegal string offset 'away' same problem with home and all other data
When trying to access data as an object I get the following error Trying to get property of non-object
I followed the tutorial to the letter. Yet im getting the basic errors above...? Any help and explanation would be appreciated. Thank you
EDIT:
var_export($schedule) returns the following:
array ( 'id' => '8e45fe2d-fb95-4504-845d-7c815623ccd6', 'year' => 2018, 'type' => 'REG', 'name' => 'REG', 'week' => array ( 'id' => '37435167-5cf6-4cce-b405-ff0e264ced9c', 'sequence' => 1, 'title' => '1', 'games' => array ( 0 => array ( 'id' => '0822b924-eadc-4398-bfe6-83cbbf3a2912', 'status' => 'scheduled', 'reference' => '57570', 'number' => 4, 'scheduled' => '2018-09-09T17:00:00+00:00', 'entry_mode' => 'INGEST', 'venue' => array ( 'id' => '6ed18563-53e0-46c2-a91d-12d73a16456d', 'name' => 'Lucas Oil Stadium', 'city' => 'Indianapolis', 'state' => 'IN', 'country' => 'USA', 'zip' => '46225', 'address' => '500 South Capitol Avenue', 'capacity' => 67000, 'surface' => 'artificial', 'roof_type' => 'retractable_dome', ), 'home' => array ( 'id' => '82cf9565-6eb9-4f01-bdbd-5aa0d472fcd9', 'name' => 'Indianapolis Colts', 'alias' => 'IND', 'game_number' => 1, ),
You are dealing with array of arrays. Try something like this:
$someArray = $jsonArray
foreach ($someArray as $key => $value) {
echo $value["home"]["name"] . ", " . $value["away"]["name"] . "<br>";
}
I need to get an JSON structure as following:
{
"emails": [
{
"sender": "shihas#abc.com",
"unread_count": 2,
"items": [
{
"id": "89",
"email": "shihas#abc.com",
"read": "0",
},
{
"id": "32",
"email": "shihas#abc.com",
"read": "0",
}
]
},
{
"sender": "marias123#gmail.com",
"unread_count": 0,
"items": [
{
"id": "2",
"email": "marias123#gmail.com",
"read": "1",
}
]
},
{
"sender": "gutar4320#hotmail.com",
"unread_count": 1,
"items": [
{
"id": "1",
"email": "gutar4320#hotmail.com",
"read": "0",
}
]
}
]
}
Array($hire_email):
In the below array I need to group all the details based on the email. And also count the no. of unread messages(i.e read = 0).
Array
(
[0] => Array
(
[id] => 89
[email] => shihas#abc.com
[read] => 0
)
[1] => Array
(
[id] => 32
[email] => shihas#abc.com
[read] => 0
)
[2] => Array
(
[id] => 2
[email] => marias123#gmail.com
[read] => 1
)
[3] => Array
(
[id] => 1
[email] => gutar4320#hotmail.com
[read] => 0
)
)
The following is the code snippet used for maintaining the JSON structure.
foreach($hire_email as $val) {
if($val['read']==0){ $count++; }else{ $count = 0;}
$hire_group_email[$val['email']]['sender'] = $val['email'];
$hire_group_email[$val['email']]['unread_count'] = $count;
$hire_group_email[$val['email']]['items'][] = $val;
}
$output["emails"][] = $hire_group_email;
echo json_encode($output);
This should do the trick.
$hire_email =array(
array(
"id" => "89",
"email" => "shihas#abc.com",
"read" => "0"
),
array
(
"id" => "32",
"email" => "shihas#abc.com",
"read" => "0"
),
array
(
"id" => "2",
"email" => "marias123#gmail.com",
"read" => "1"
),
array
(
"id" => "1",
"email" => "gutar4320#hotmail.com",
"read" => "0"
)
);
$tmp = array();
foreach($hire_email as $arg)
{
$tmp[$arg['email']][] = $arg;
}
$output = array();
foreach($tmp as $type => $labels)
{
$count = 0;
foreach ($labels as $value) {
if($value['read']==0){ $count++; }else{ $count = 0;}
}
$output[] = array(
'sender' => $type,
'unread_count' => $count,
'items' => $labels
);
}
echo json_encode($output);
Try doing it like this, using: array_sum and array_column, the rest is just picking out the first items values.
$array = json_decode($json, true)['emails'];
$result = [];
foreach($array as $val) {
$result[] = [
'id' => $val['items'][0]['id'],
'email' => $val['items'][0]['email'],
'read' => array_sum(array_column($val['items'], 'read'))
];
}
$output["emails"] = $result;
echo json_encode($output, JSON_PRETTY_PRINT);
Result:
{
"emails": [
{
"id": "89",
"email": "shihas#abc.com",
"read": 0
},
{
"id": "2",
"email": "marias123#gmail.com",
"read": 1
},
{
"id": "1",
"email": "gutar4320#hotmail.com",
"read": 0
}
]
}
https://3v4l.org/hi7qm
And if you want it as shown ;p (my mistake, misread it):
Loop over each item, then loop over the items and use that to build the output.
$array = json_decode($json, true)['emails'];
$result = [];
foreach($array as $val) {
foreach ($val['items'] as $item) {
$result[] = [
'id' => $item['id'],
'email' => $item['email'],
'read' => array_sum(array_column($val['items'], 'read'))
];
}
}
$output["emails"] = $result;
echo json_encode($output, JSON_PRETTY_PRINT);
Result:
{
"emails": [
{
"id": "89",
"email": "shihas#abc.com",
"read": 0
},
{
"id": "32",
"email": "shihas#abc.com",
"read": 0
},
{
"id": "2",
"email": "marias123#gmail.com",
"read": 1
},
{
"id": "1",
"email": "gutar4320#hotmail.com",
"read": 0
}
]
}
https://3v4l.org/eU95A