So I'm having a strange problem with Doctrine that I don't understand and need help with. Essentially, I am running quite a complex query due to the nature of my database and its various joins and for some reason the response when I grab try to grab all records from my database is returning my entities incorrectly.
See my doctrine query below:
$subQuery = $this->_em->createQueryBuilder()
->from(Product::class, 'ex')
->select('ppsi.id')
->join('ex.productSpecificationItems', 'ppsi')
->where('ex.id = p.id');
$subQuery = $subQuery->getDQL();
$subQuery2 = $this->_em->createQueryBuilder()
->from(Product::class, 'ex2')
->select('ppoiv.id')
->join('ex2.productOptionItemValues', 'ppoiv')
->where('ex2.id = p.id');
$subQuery2 = $subQuery2->getDQL();
$subQuery3 = $this->_em->createQueryBuilder()
->from(Product::class, 'ex3')
->select('poie.id')
->join('ex3.productOptionItems', 'poie')
->where('ex3.id = p.id');
$subQuery3 = $subQuery3->getDQL();
$qb = $this->createQueryBuilder('p')
->select('p, pc, psc, i, po, poi, poiv, ps, psi')
->join('p.productCategory', 'pc')
->leftJoin('p.productSubCategory', 'psc')
->leftJoin('p.images', 'i')
->leftJoin('p.productOptions', 'po')
->leftJoin('p.productSpecifications', 'ps')
->leftJoin('ps.productSpecificationItems', 'psi', Join::WITH, 'psi.id IN (' . $subQuery. ')')
->leftJoin('po.productOptionItems', 'poi', Join::WITH, 'poi.id IN (' . $subQuery3. ')')
->leftJoin('poi.productOptionItemValue', 'poiv', Join::WITH, 'poiv.id IN (' . $subQuery2. ')')
->addOrderBy('p.id', 'ASC');
The response of this causes some entities to have the productOptionItemValues either listed under the wrong productOptionItem, just causes blank records to return, or doesn't return them at all. See an example below (as a JSON for clarity):
{
"id": 373,
"name": "test",
"code": "test",
"url": "373-test",
"price": "1.00",
"stock": 1,
"description": "<p>fghfgh mnsdbfksdhfjk sd</p>\n",
"live": false,
"createdAt": "2022-03-17T14:45:35+00:00",
"updatedAt": "2022-03-17T15:12:44+00:00",
"featured": false,
"aggregateReviewScore": null,
"productCategory": {
"id": 2,
"name": "Hex Set Screws",
"url": "hex-set-screws"
},
"productSubCategory": {
"id": 12,
"name": "Nylon",
"url": "nylon"
},
"images": [],
"productOptions": [
{
"id": 1,
"name": "Colour",
"productOptionItems": {
"0": {
"id": 2,
"name": "Black",
"productOptionItemValue": [
{
"id": 1196,
"stock": 1,
"price": "1.00",
"useOwn": false
},
{
"id": 1201,
"stock": 1,
"price": "1.00",
"useOwn": false
},
{
"id": 1198,
"stock": 1,
"price": "1.00",
"useOwn": false
}
]
},
"1": {
"id": 8,
"name": "Yellow",
"productOptionItemValue": [
{
"id": 1197,
"stock": 1,
"price": "1.00",
"useOwn": false
}
]
},
"2": {
"id": 14,
"name": "Light Grey"
},
"3": null,
"4": {
"id": 15,
"name": "Mid Grey"
},
"7": null,
"8": {
"id": 20,
"name": "Light Blue"
},
"11": null,
"12": {
"id": 22,
"name": "Purple"
},
"13": null
}
},
{
"id": 2,
"name": "Pack Size",
"productOptionItems": [
{
"id": 3,
"name": "10",
"productOptionItemValue": [
{
"id": 1180,
"stock": 100,
"price": "10.00",
"useOwn": true
}
]
},
{
"id": 4,
"name": "100",
"productOptionItemValue": [
{
"id": 1181,
"stock": 10,
"price": "1000.00",
"useOwn": true
}
]
}
]
}
],
"productSpecifications": []
}
If I run the same query on a SINGLE product (so the same Doctrine Query as a above just with a p.id = :id WHERE added) it returns absolutely fine. See the response for that below (and the CORRECT response I am looking for):
{
"id": 373,
"name": "test",
"code": "test",
"url": "373-test",
"price": 1,
"stock": 1,
"description": "<p>fghfgh mnsdbfksdhfjk sd</p>\n",
"live": false,
"createdAt": "2022-03-17T14:45:35+00:00",
"updatedAt": "2022-03-17T15:12:44+00:00",
"featured": false,
"aggregateReviewScore": null,
"productCategory": {
"id": 2,
"name": "Hex Set Screws",
"url": "hex-set-screws"
},
"productSubCategory": {
"id": 12,
"name": "Nylon",
"url": "nylon"
},
"images": [],
"productOptions": [
{
"id": 1,
"name": "Colour",
"productOptionItems": [
{
"id": 2,
"name": "Black",
"productOptionItemValue": {
"id": 1196,
"stock": 1,
"price": 1,
"useOwn": false
}
},
{
"id": 7,
"name": "Red",
"productOptionItemValue": {
"id": 1201,
"stock": 1,
"price": 1,
"useOwn": false
}
},
{
"id": 8,
"name": "Yellow",
"productOptionItemValue": {
"id": 1197,
"stock": 1,
"price": 1,
"useOwn": false
}
},
{
"id": 14,
"name": "Light Grey",
"productOptionItemValue": {
"id": 1202,
"stock": 1,
"price": 1,
"useOwn": false
}
},
{
"id": 15,
"name": "Mid Grey",
"productOptionItemValue": {
"id": 1205,
"stock": 1,
"price": 1,
"useOwn": false
}
},
{
"id": 20,
"name": "Light Blue",
"productOptionItemValue": {
"id": 1203,
"stock": 1,
"price": 1,
"useOwn": false
}
},
{
"id": 22,
"name": "Purple",
"productOptionItemValue": {
"id": 1204,
"stock": 1,
"price": 1,
"useOwn": false
}
},
{
"id": 23,
"name": "Natural",
"productOptionItemValue": {
"id": 1198,
"stock": 1,
"price": 1,
"useOwn": false
}
}
]
},
{
"id": 2,
"name": "Pack Size",
"productOptionItems": [
{
"id": 3,
"name": "10",
"productOptionItemValue": {
"id": 1180,
"stock": 100,
"price": 10,
"useOwn": true
}
},
{
"id": 4,
"name": "100",
"productOptionItemValue": {
"id": 1181,
"stock": 10,
"price": 1000,
"useOwn": true
}
}
]
}
],
"productSpecifications": []
}
Any help or ideas would be greatly appreciated!
Related
I have created a JSON for avalara request, line items are 10 in count. But it is always showing error as -
code:ErrorCountLimitExceededError
number:1722
message : The request has exceeded the maximum number of validation errors.
When I reduce the line item to count 6, it works fine. but my requirement is more than that.
The same JSON is working fine in postman.
Following is the JSON which I had used-
{
"lines": [
{
"number": "1",
"quantity": 1,
"amount": 100,
"taxCode": "PS081282",
"itemCode": "Y0001GHGH",
"description": "TEST"
},
{
"number": "2",
"quantity": 1,
"amount": 100,
"taxCode": "PS081282A",
"itemCode": "TTTTYYYA",
"description": "TEST"
},
{
"number": "3",
"quantity": 1,
"amount": 190,
"taxCode": "PS081282B",
"itemCode": "HGHGHG0001B",
"description": "TEST"
},
{
"number": "4",
"quantity": 1,
"amount": 2300,
"taxCode": "PS081282C",
"itemCode": "PKOO0001C",
"description": "TEST"
},
{
"number": "5",
"quantity": 1,
"amount": 200,
"taxCode": "PS081282D",
"itemCode": "ABCF567",
"description": "TEST"
},
{
"number": "6",
"quantity": 1,
"amount": 10990,
"taxCode": "PS081282E",
"itemCode": "Y00DSD01E",
"description": "TEST"
},
{
"number": "7",
"quantity": 1,
"amount": 140,
"taxCode": "PS081282F",
"itemCode": "Y00GJG232",
"description": "TEST"
},
{
"number": "8",
"quantity": 1,
"amount": 100,
"taxCode": "PS081282F2X",
"itemCode": "65HGFH675",
"description": "TEST"
}
],
"type": "SalesInvoice",
"companyCode": "DEFAULT",
"date": "2023-01-10",
"customerCode": "ABC",
"purchaseOrderNo": "2023-01-10-001",
"addresses": {
"singleLocation": {
"line1": "2000 Main Street",
"city": "Irvine",
"region": "CA",
"country": "US",
"postalCode": "92614"
}
},
"commit": true,
"currencyCode": "USD",
"description": "Yarn"
}
Sorry for the confusing title. I am having a bit of an issue here merging some JSON files. I need to merge all the products into one array in a separate file.
I have a directory full of same structured json files. I am using glob to select all files and decode->append-->encode json files into one large file.
Here is my code:
<?php
$files = glob("*.json");
$newDataArray = [];
foreach($files as $file){
$thisData = file_get_contents($file);
$thisDataArray = json_decode($thisData);
$newDataArray[] = $thisDataArray;
}
$newDataJSON = json_encode($newDataArray);
file_put_contents("merged.json",$newDataJSON);
?>
Now, the above code seems to work great but I only want to extract all the products.
Quick example of what I need to achieve.
File1.json
{
"status": true,
"user": {
"username": "sally",
"avatar": "/images/default-avatar.png",
"products": [
{
"id": "35vR4hr",
"title": "Picture 1",
"image": null,
"quantity": {
"min": 1,
"max": 1
},
"price": 2,
"currency": "CAD",
"stock_warning": 1,
"type": "service",
"stock": 9223372036854776000
},
{
"id": "na1Id4t",
"title": "Picture 2",
"image": null,
"quantity": {
"min": 1,
"max": 1
},
"price": 0.75,
"currency": "CAD",
"stock_warning": 3,
"type": "service",
"stock": 9223372036854776000
}
]
}
}
File2.json
{
"status": true,
"user": {
"username": "Jessica",
"avatar": "/images/default-avatar.png",
"products": [
{
"id": "wjiefi94",
"title": "Picture 3",
"image": null,
"quantity": {
"min": 1,
"max": 1
},
"price": 2,
"currency": "CAD",
"stock_warning": 1,
"type": "service",
"stock": 9223372036854776000
},
{
"id": "n34idwi",
"title": "Picture 4",
"image": null,
"quantity": {
"min": 1,
"max": 1
},
"price": 0.75,
"currency": "CAD",
"stock_warning": 3,
"type": "service",
"stock": 9223372036854776000
}
]
}
}
I want the data to be merged like:
merged.json
{
"products": [
{
"id": "wjiefi94",
"title": "Picture 1",
"image": null,
"quantity": {
"min": 1,
"max": 1
},
"price": 2,
"currency": "CAD",
"stock_warning": 1,
"type": "service",
"stock": 9223372036854776000
},
{
"id": "n34idwi",
"title": "Picture 2",
"image": null,
"quantity": {
"min": 1,
"max": 1
},
"price": 0.75,
"currency": "CAD",
"stock_warning": 3,
"type": "service",
"stock": 9223372036854776000
},
{
"id": "n34idwi",
"title": "Picture 3",
"image": null,
"quantity": {
"min": 1,
"max": 1
},
"price": 0.75,
"currency": "CAD",
"stock_warning": 3,
"type": "service",
"stock": 9223372036854776000
},
{
"id": "n34idwi",
"title": "Picture 4",
"image": null,
"quantity": {
"min": 1,
"max": 1
},
"price": 0.75,
"currency": "CAD",
"stock_warning": 3,
"type": "service",
"stock": 9223372036854776000
}
]
}
I hope this makes sense. I feel like I have hit a dead end here. Any help is greatly appreciated.
would it be possible for you to call an external tool like "jq"? handling json (just like csv), especially with many files, is not something you should be doing manually.
btw, your example does not have commas between products 2 and 3 and 3 and 4.
Your new code on line 5 should probably read like this with the array brackets? Otherwise you are overwriting the contents of the last files:
$thisDataArray[] = json_decode($thisData);
And why are you merging products from Sally and Jessica into the same user? Maybe you can just extract all the products objects into one file?
More of a code review than an answer, hope it helps ;)
I am using php wrapper, try create an item, all is ok, item is creating, but I can't change status, tried different ways, but can't find right way.
Need change status to "Closed" - http://prntscr.com/fsrwc3
Codes not works:
$fields = new PodioItemFieldCollection([
new PodioCategoryItemField(['external_id'=>'status', 'values'=>13]),
]);
$item = new PodioItem([
'app' => new PodioApp($app_id),
'fields' => $fields
]);
$item->save();
or
$fields = new PodioItemFieldCollection([
new PodioCategoryItemField(['external_id'=>'status', 'values'=>13]),
]);
$item = new PodioItem([
'app' => new PodioApp($app_id),
'fields' => $fields
]);
$item->save();
$get_item = PodioItem::get_basic($item->item_id);
$get_item->fields['status']->values = ['id'=>13];
$get_item->save();
After create item (after new PodioItem...), if I get fields after this code (just get $item->fields or PodioItem::get_basic...), I can see correct status, only in the code, only immediatly after create item, but if I get this item in the another code (just PodioItem::get_basic...) I will see default value, so code don't change status, looks like I just see some cache.
If I create item on the one script:
$fields = new PodioItemFieldCollection([
new PodioCategoryItemField(['external_id'=>'status', 'values'=>13]),
]);
$item = new PodioItem([
'app' => new PodioApp($app_id),
'fields' => $fields
]);
$item->save();
Then, in the another script update field, it will be change:
$get_item = PodioItem::get_basic('639637317');
$get_item->fields['status']->values = ['id'=>13];
$get_item->save();
Update - debug information:
Get log by test code -
PodioItem::create($app_id, ['fields' => ['status'=>[13], 'category'=>[3], 'contract-type'=>[4]]]);
(simple variant for creating an item, have the same problems like new PodioItem... )
All fields have category type, but:
status - have inline show type - don't chnages
category - have dropdown show type - Is changing
contract-type - have dropdown show type - Is changing
Log:
2017-07-08 11:07:22 200 POST /item/app/12152727/
2017-07-08 11:07:22 Request body: {"fields":{"status":[8],"category":[3],"contract-type":[4]}}
2017-07-08 11:07:22 Reponse: {
"presence": {
"ref_type": "item",
"ref_id": 641331142,
"user_id": 4194774,
"signature": "c165b85090e6ad28e74ae4baf93ee56113f88bc9"
},
"app": {
"status": "active",
"sharefile_vault_url": null,
"name": "Projects",
"default_view_id": null,
"url_add": "https:\/\/podio.com\/acs-1com\/project-management\/apps\/projects\/items\/new",
"icon_id": 378,
"link_add": "https:\/\/podio.com\/acs-1com\/project-management\/apps\/projects\/items\/new",
"app_id": 12152727,
"current_revision": 141,
"item_name": "Project",
"link": "https:\/\/podio.com\/acs-1com\/project-management\/apps\/projects",
"url": "https:\/\/podio.com\/acs-1com\/project-management\/apps\/projects",
"url_label": "projects",
"config": {
"item_name": "Project",
"icon_id": 378,
"type": "standard",
"name": "Projects",
"icon": "378.png"
},
"space_id": 3466816,
"icon": "378.png"
},
"created_on": "2017-07-10 15:31:16",
"last_event_on": "2017-07-10 15:31:16",
"linked_account_data": null,
"sharefile_vault_folder_id": null,
"app_item_id_formatted": "3988",
"recurrence": null,
"title": "ACSC",
"participants": {},
"created_by": {
"user_id": 4194774,
"name": "Anton Mikhailov",
"url": "https:\/\/podio.com\/users\/4194774",
"type": "user",
"image": null,
"avatar_type": "file",
"avatar": null,
"id": 4194774,
"avatar_id": null,
"last_seen_on": "2017-07-10 15:31:15"
},
"priority": 641331142.0,
"created_via": {
"url": null,
"auth_client_id": 25162,
"display": true,
"name": "importer",
"id": 25162
},
"subscribed_count": 1,
"reminder": null,
"ref": null,
"revision": 0,
"app_item_id": 3988,
"link": "https:\/\/podio.com\/acs-1com\/project-management\/apps\/projects\/items\/3988",
"item_id": 641331142,
"sharefile_vault_url": null,
"rights": ["subscribe", "grant", "add_conversation", "rate", "update", "delete", "add_file", "grant_view", "view", "comment", "add_task"],
"fields": [{
"status": "active",
"type": "category",
"field_id": 93352415,
"label": "Division",
"values": [{
"value": {
"status": "active",
"text": "ACSC",
"id": 3,
"color": "D2E4EB"
}
}],
"config": {
"default_value": null,
"unique": false,
"description": null,
"hidden_create_view_edit": false,
"required": true,
"mapping": null,
"label": "Division",
"visible": true,
"delta": 5,
"hidden": false,
"settings": {
"multiple": false,
"options": [{
"status": "active",
"text": "ACSE",
"id": 1,
"color": "DCEBD8"
}, {
"status": "active",
"text": "ACSB",
"id": 2,
"color": "F7F0C5"
}, {
"status": "active",
"text": "ACSC",
"id": 3,
"color": "D2E4EB"
}],
"display": "dropdown"
}
},
"external_id": "category"
}, {
"status": "active",
"type": "category",
"field_id": 148215928,
"label": "Contract Type",
"values": [{
"value": {
"status": "active",
"text": "No Contract",
"id": 4,
"color": "DDDDDD"
}
}],
"config": {
"default_value": null,
"unique": false,
"description": null,
"hidden_create_view_edit": false,
"required": true,
"mapping": null,
"label": "Contract Type",
"visible": true,
"delta": 7,
"hidden": false,
"settings": {
"multiple": false,
"options": [{
"status": "active",
"text": "PO \/ Purchase \/ T&M",
"id": 1,
"color": "FFD5C2"
}, {
"status": "active",
"text": "Original Contract",
"id": 2,
"color": "D2E4EB"
}, {
"status": "active",
"text": "Service Rider",
"id": 3,
"color": "DCEBD8"
}, {
"status": "active",
"text": "No Contract",
"id": 4,
"color": "DDDDDD"
}],
"display": "dropdown"
}
},
"external_id": "contract-type"
}, {
"status": "active",
"type": "category",
"field_id": 93034840,
"label": "Instal Status",
"values": [{
"value": {
"status": "active",
"text": "Closed",
"id": 13,
"color": "E1D8ED"
}
}],
"config": {
"default_value": null,
"unique": false,
"description": null,
"hidden_create_view_edit": false,
"required": true,
"mapping": null,
"label": "Instal Status",
"visible": true,
"delta": 13,
"hidden": false,
"settings": {
"multiple": false,
"options": [{
"status": "deleted",
"text": "To Be Reviewed",
"id": 2,
"color": "F7F0C5"
}, {
"status": "deleted",
"text": "ACS Accounting Review",
"id": 5,
"color": "FFD5C2"
}, {
"status": "deleted",
"text": "Ignite Setup",
"id": 10,
"color": "DCEBD8"
}, {
"status": "active",
"text": "To Be Scheduled",
"id": 8,
"color": "D2E4EB"
}, {
"status": "active",
"text": "In Progress",
"id": 6,
"color": "DCEBD8"
}, {
"status": "active",
"text": "Warranty",
"id": 11,
"color": "F7F0C5"
}, {
"status": "active",
"text": "Complete",
"id": 3,
"color": "D1F3EC"
}, {
"status": "deleted",
"text": "Closed",
"id": 7,
"color": "DDDDDD"
}, {
"status": "active",
"text": "Cancelled",
"id": 9,
"color": "DDDDDD"
}, {
"status": "deleted",
"text": "VA in Progress",
"id": 4,
"color": "E1D8ED"
}, {
"status": "deleted",
"text": "Submitted",
"id": 1,
"color": "F7F0C5"
}, {
"status": "active",
"text": "On Hold",
"id": 12,
"color": "F7D1D0"
}, {
"status": "active",
"text": "Closed",
"id": 13,
"color": "E1D8ED"
}],
"display": "inline"
}
},
"external_id": "status"
}],
"initial_revision": {
"item_revision_id": 1664054437,
"created_via": {
"url": null,
"auth_client_id": 25162,
"display": true,
"name": "importer",
"id": 25162
},
"created_by": {
"user_id": 4194774,
"name": "Anton Mikhailov",
"url": "https:\/\/podio.com\/users\/4194774",
"type": "user",
"image": null,
"avatar_type": "file",
"avatar": null,
"id": 4194774,
"avatar_id": null,
"last_seen_on": "2017-07-10 15:31:15"
},
"created_on": "2017-07-10 15:31:16",
"user": {
"user_id": 4194774,
"name": "Anton Mikhailov",
"url": "https:\/\/podio.com\/users\/4194774",
"type": "user",
"image": null,
"avatar_type": "file",
"avatar": null,
"id": 4194774,
"avatar_id": null,
"last_seen_on": "2017-07-10 15:31:15"
},
"type": "creation",
"revision": 0
},
"current_revision": {
"item_revision_id": 1664054437,
"created_via": {
"url": null,
"auth_client_id": 25162,
"display": true,
"name": "importer",
"id": 25162
},
"created_by": {
"user_id": 4194774,
"name": "Anton Mikhailov",
"url": "https:\/\/podio.com\/users\/4194774",
"type": "user",
"image": null,
"avatar_type": "file",
"avatar": null,
"id": 4194774,
"avatar_id": null,
"last_seen_on": "2017-07-10 15:31:15"
},
"created_on": "2017-07-10 15:31:16",
"user": {
"user_id": 4194774,
"name": "Anton Mikhailov",
"url": "https:\/\/podio.com\/users\/4194774",
"type": "user",
"image": null,
"avatar_type": "file",
"avatar": null,
"id": 4194774,
"avatar_id": null,
"last_seen_on": "2017-07-10 15:31:15"
},
"type": "creation",
"revision": 0
},
"linked_account_id": null,
"push": {
"timestamp": 1499700676,
"expires_in": 21600,
"channel": "\/item\/641331142",
"signature": "b8a816ff367da6bc730071c875ca3fdca2d2c344"
},
"external_id": null
}
Have you tried http://podio.github.io/podio-php/fields/#category-field ?
Setting values
Set a single value by using the option_id. You can also
add a value with add_value()
$item = PodioItem::get_basic(123);
$field_id = 'category';
// Set value to a single option
$item->fields[$field_id]->values = 4; // option_id=4
// Add value to existing selection
$item->fields[$field_id]->add_value(4); // option_id=4
Use an array to set multiple values
$item = PodioItem::get_basic(123);
$field_id = 'category';
$item->fields[$field_id]->values = array(4,5,6); // option_ids: 4, 5 and 6
Creating item with value:
$fields = new PodioItemFieldCollection([
new PodioCategoryItemField(['external_id'=>'status', 'values'=>array(13)]),
]);
$item = new PodioItem([
'app' => new PodioApp($app_id),
'fields' => $fields
]);
$item->save();
So I have
{
"members": [
{
"username": "John",
"status": "offline",
"avatar_url": "...",
"id": "830232882252102064"
},
{
"username": "Momo",
"status": "online",
"avatar_url": "...",
"id": "259137993351102464"
}
]
}
How do I count (in php) how many users are offline and how many users are online and return them into a value like $memonline and $memoffline.
Here in below code we are getting values of all statuses and then we are counting values of all statuses.
Try this code snippet here
<?php
ini_set('display_errors', 1);
$string='{
"channels": [
{
"position": 13,
"id": "304700935878213642",
"name": "20KBPS"
},
{
"position": 12,
"id": "304700895978061835",
"name": "50KBPS"
},
{
"position": 11,
"id": "304701193261809672",
"name": "70KBPS"
},
{
"position": 10,
"id": "304701326288224256",
"name": "90KBPS"
},
{
"position": 1,
"id": "304699877621891072",
"name": "=================="
},
{
"position": 9,
"id": "304700570592346114",
"name": "=================="
},
{
"position": 4,
"id": "304701407221514240",
"name": "=================="
},
{
"position": 14,
"id": "304700808883339264",
"name": "=================="
},
{
"position": 2,
"id": "304700525939523584",
"name": "Channel 1"
},
{
"position": 3,
"id": "304700547426942976",
"name": "Channel 2"
},
{
"position": 0,
"id": "304692483973971990",
"name": "General Channel"
},
{
"position": 6,
"id": "304701637446991873",
"name": "Private/2"
},
{
"position": 5,
"id": "304701480605319178",
"name": "Private/2"
},
{
"position": 7,
"id": "304701680010788866",
"name": "Private/3"
},
{
"position": 8,
"id": "304701738999611394",
"name": "Private/3"
},
{
"position": 15,
"id": "304700776691793921",
"name": "Trash Bin"
}
],
"instant_invite": null,
"id": "304692483973971989",
"members": [
{
"username": "Dyno",
"status": "online",
"bot": true,
"game": {
"name": "dynobot.net | ?help"
},
"avatar_url": "https://cdn.discordapp.com/avatars/155149108183695360/5aeb68c29b56b3d92eddb6f46df5051c.jpg",
"avatar": "5aeb68c29b56b3d92eddb6f46df5051c",
"discriminator": "3861",
"id": "155149108183695360"
},
{
"username": "Momo",
"status": "online",
"bot": true,
"game": {
"name": "$help | $info"
},
"avatar_url": "https://cdn.discordapp.com/avatars/259137993351102464/a3005ab7aff3eb829fecf375931a76f1.jpg",
"avatar": "a3005ab7aff3eb829fecf375931a76f1",
"discriminator": "4649",
"id": "259137993351102464"
},
{
"username": "Ronny Dark",
"status": "online",
"avatar_url": "https://cdn.discordapp.com/avatars/152855546574143492/6d9b98972ca6f0308be4dd2aec5aaca3.jpg",
"avatar": "6d9b98972ca6f0308be4dd2aec5aaca3",
"discriminator": "1480",
"id": "152855546574143492"
}
],
"name": "Server name"
}';
$array=json_decode($string,true);
$result=array_column($array["members"],"status");
$members=array_count_values($result);
echo isset($members["offline"]) ? $members["offline"] : 0;
I am trying to get some specific fields out of this Json.
fn({
"processingDurationMillis": 454,
"authorisedAPI": true,
"success": true,
"airline": "MH",
"validCreditCards": [
"AX",
"CA",
"VI"
],
"paypal": true,
"outboundOptions": [
{
"optionId": 0,
"flights": [
{
"flightNumber": "0066",
"departureAirport": {
"code": "KUL",
"name": "Kuala Lumpur Intl",
"city": "Kuala Lumpur",
"country": "Malaysia",
"timezone": "Asia/Kuala_Lumpur",
"lat": 2.745578,
"lng": 101.709917,
"terminal": null,
"gate": null
},
"arrivalAirport": {
"code": "ICN",
"name": "Incheon Intl",
"city": "Seoul",
"country": "South Korea",
"timezone": "Asia/Seoul",
"lat": 37.469075,
"lng": 126.450517,
"terminal": null,
"gate": null
},
"marketingAirline": "MH",
"mealIndicator": "M",
"allowedSsrs": {
},
"operatingAirline": null,
"equipment": "333",
"equipmentName": "Airbus A330-300",
"flightRPH": 10101,
"comments": [
"MH CODESHARE WITH KE"
],
"depScheduled": "2015-04-28T23:30:00.000+08:00",
"arrScheduled": "2015-04-29T07:10:00.000+09:00",
"depEstimated": null,
"depActual": null,
"arrEstimated": null,
"arrActual": null,
"eligibleForEticketing": true,
"cabin": "ECONOMY",
"fareMarketingType": "BASIC",
"rbd": "N",
"seatsAvailable": 9,
"durationMinutes": 400,
"minutesToScheduledFlightDeparture": 6486
}
],
"stopOvers": [
],
"fareDetails": {
"perPassengerJourneyFares": [
{
"passengerType": "ADT",
"fare": "1214.95",
"currencyCode": "MYR"
}
],
"perPassengerTripTaxes": [
{
"passengerType": "ADT",
"totalTax": "68.90",
"taxes": [
{
"code": "MY",
"amount": "65.00",
"currency": "MYR"
},
{
"code": "D8",
"amount": "3.90",
"currency": "MYR"
}
]
}
],
"journeyFare": "1214.95",
"totalTripFare": "1283.90",
"fareCurrency": "MYR"
},
"magicString": "2t2qi8oNXWkrDR75zYDrk9+3wNaJBzHyK1ftoR/VZPVgHO+EFTkh8DMg5WUl1ap7VjwBsnhD2gFxAwBbHhY0+k0lp7BUvSoYSKg6S6u4ZkvbIWMktl+lHgcKl46vht9//2dZVJvH4D7WJvnJTtK5O4TWNrkiTmEdHp55yRmjwWfsgNswOIMXoWrZj3OUJ4DH4POJ8rmfilimvtpBCdxNsqoZDVC9d6/6LiICZ3wHZJ7w/88QuExFV7OsHbc+jI3trRzDCCb6Ns62MGyfsXX6Pz8mJe6gs02UjapVSPa3M9CqLGMCN0xCF28WNbavhSI9jG3cWsQbxGU8rnhmjx00Iw5v2qqjdE/Dx432Qzs4s36SqUjLF7KN9hAJoQuMX3emE4gZ+7ANJ5bDTDEYZlnUZ4iXKykzUptYDyGay0evu1kdCjxPJlgiEtOl3hFMaKC+eoTsjps4RoYy0Z7oD3aP52qCYPdCH+8XTic522UKU1mW9HMjmGxH5zrvYK2rOgzSR2+xH5K3IpXHBAQqWOTEvmirP4qvg5VOPjyO9mIM83I6aY1JAkqo9jYqtEwrGqANdhA9z78EdoyQYKZBXcLsQMKz06fAczwk/WxxIi1ctL8EW+aZYddkbPo7xD6NWc8bJ+ARw5AlS1tirVNcO3mN5jVr/a6qftVuaz/0q83VsX4ztQpgMjDkptbw9Zz6DNLgiLJEzdf7fraoVUyzeth5wucOMzpLBP+ERbD7XFnDSKN8QzG6lLpDK8qy95K5FMmcF4uDq8Y1waTyIN9sS+v50OTbjr7Ebs3uKIxMZFfGUfp7YpDiVyo+2x4La4K7rhHPtoR6iEfVCjnTAUvamQu3qgL3vuSCPPPJiHFbdOrKVlp3kfAxaIcJpX3Z+Twx2cNAhsGHSk2ZazzvP5Pw1EF066VcoDkld9Oe/Qu5cC+DtG2LHhMA7NU8hMD66q9UCsXC6P/mjbKr7hatjHyyklDIKuxxirMpYkukEa73RJlhKmC0fjj4EYcgRy5MtybexuN59KaTeSEFxMGFIkv0zHp5jO/wHUvyypqbxTKFR3VAx6WpmSNg/Iui2uXDhNu/F4zJnYQUW9EyluZEPebFk2Uj455O2+y0UmFe4WnUY+0d92obZNv855/ctA4UC/LQn2s9azqdhDIeUUHuHEn2a4Grb+7l8wuai6ybBmmE62ck+CqMou+A+CUwk71KMkh3ZXf8BdeelW8Ia7r9ja7wKNBklgYo4Q8xOR63QhyCt2BiiR9aOxiDIKiW7bxSFCBga7yIPWx/NZdGjUYTuiJ9KZ7W2dKLhF6XDU5mWOV7XwMRzkyschEnjSzQWGjTTftEIiNI1V1M2bhFwc92JkfVFxwXCg==",
"seatsAvailable": [
9
],
"corporateAccount": false,
"flightCanBeHeld": true,
"durationMinutes": 400,
"gaFareDetails": {
"perPassengerJourneyFares": [
{
"passengerType": "ADT",
"fare": "1214.95",
"currencyCode": "MYR"
}
],
"perPassengerTripTaxes": [
{
"passengerType": "ADT",
"totalTax": "68.90",
"taxes": [
{
"code": "MY",
"amount": "65.00",
"currency": "MYR"
},
{
"code": "D8",
"amount": "3.90",
"currency": "MYR"
}
]
}
],
"journeyFare": "1214.95",
"totalTripFare": "1283.90",
"fareCurrency": "MYR"
},
"adobeFareDetails": {
"perPassengerJourneyFares": [
{
"passengerType": "ADT",
"fare": "336.66",
"currencyCode": "USD"
}
],
"perPassengerTripTaxes": [
{
"passengerType": "ADT",
"totalTax": "19.09",
"taxes": [
{
"code": "MY",
"amount": "18.01",
"currency": "USD"
},
{
"code": "D8",
"amount": "1.08",
"currency": "USD"
}
]
}
],
"journeyFare": "336.66",
"totalTripFare": "355.77",
"fareCurrency": "USD"
},
"userAgentFareDetails": {
"perPassengerJourneyFares": [
{
"passengerType": "ADT",
"fare": "336.66",
"currencyCode": "USD"
}
],
"perPassengerTripTaxes": [
{
"passengerType": "ADT",
"totalTax": "19.09",
"taxes": [
{
"code": "MY",
"amount": "18.01",
"currency": "USD"
},
{
"code": "D8",
"amount": "1.08",
"currency": "USD"
}
]
}
],
"journeyFare": "336.66",
"totalTripFare": "355.77",
"fareCurrency": "USD"
},
"eligibleForeTicketing": true,
"lowestSeatCount": 9,
"directFlight": true
}
],
"departureAirport": {
"code": "KUL",
"name": "Kuala Lumpur Intl",
"city": "Kuala Lumpur",
"country": "Malaysia",
"timezone": "Asia/Kuala_Lumpur",
"lat": 2.745578,
"lng": 101.709917,
"terminal": null,
"gate": null
},
"arrivalAirport": {
"code": "ICN",
"name": "Incheon Intl",
"city": "Seoul",
"country": "South Korea",
"timezone": "Asia/Seoul",
"lat": 37.469075,
"lng": 126.450517,
"terminal": null,
"gate": null
},
"apiRequired": true,
"fareRules": [
{
"id": 50,
"order": 1,
"priority": 0,
"code": "Basic",
"name": "MHbasic",
"value": "Economy Class Fares",
"listFareRules": [
{
"id": 130,
"order": 0,
"code": "",
"name": "Discount level",
"value": "Up to 65%"
},
{
"id": 140,
"order": 1,
"code": "",
"name": "Where to buy",
"value": "All channels"
},
{
"id": 150,
"order": 2,
"code": "",
"name": "Advance purchase",
"value": "Applies"
},
{
"id": 160,
"order": 3,
"code": "",
"name": "Payment",
"value": "Ticket dateline applies"
},
{
"id": 170,
"order": 4,
"code": "",
"name": "Baggage allowance",
"value": "2pc/30kg"
},
{
"id": 180,
"order": 5,
"code": "",
"name": "Advance seat selection",
"value": "Not allowed"
},
{
"id": 190,
"order": 6,
"code": "",
"name": "Enrich miles",
"value": "Nil"
},
{
"id": 200,
"order": 7,
"code": "",
"name": "Change of booking",
"value": "Not allowed"
},
{
"id": 210,
"order": 8,
"code": "",
"name": "Upgrade",
"value": "Not allowed"
},
{
"id": 220,
"order": 9,
"code": "",
"name": "Stand by at the airport",
"value": "For a fee"
},
{
"id": 220,
"order": 10,
"code": "",
"name": "No show",
"value": "Penalty applies"
},
{
"id": 230,
"order": 11,
"code": "",
"name": "Refund",
"value": "For a fee"
}
],
"listFareNotes": [
{
"id": 10,
"order": 0,
"code": "",
"name": "Important Notice",
"value": ""
},
{
"id": 15,
"order": 1,
"code": "",
"name": "",
"value": ""
},
{
"id": 20,
"order": 2,
"code": "",
"name": "1.",
"value": "Generic attributes shown only applies to MH operated flights. MH3000-3999, MH5200-5999 and MH9000-9999 Series flights are subject to their own rules. Please contact MH Call Center or ticket offices for actual fare rules."
},
{
"id": 30,
"order": 3,
"code": "",
"name": "2.",
"value": "For transpacific and transatlantic flights, the following baggage allowances apply: Economy - 2 pieces (23kg each piece), First and Business - 2 pieces (32kg each piece)."
},
{
"id": 50,
"order": 5,
"code": "",
"name": "3.",
"value": "Upgrade, standby at the airport and refund fees for specific routes can be obtained from subsequent booking pages."
},
{
"id": 60,
"order": 6,
"code": "",
"name": "4.",
"value": "Standby at the airport denotes the same day for an earlier flight."
},
{
"id": 70,
"order": 7,
"code": "",
"name": "5.",
"value": "Fare rules shown are indicative only. Please call our Contact Center to check the detailed fare rules."
},
{
"id": 80,
"order": 8,
"code": "",
"name": "",
"value": "Should there be any discrepancy between the above information and the terms and conditions (T&C) published in the fare rules, then the T&C in the fare rules shall prevail."
}
]
}
],
"Errors": [
],
"Warnings": [
]
})
i want extract flight number, depScheduled, arrScheduled and journey fare from the above json.
here are my code:
$json2 = json_decode($json,true);
$result= array();
foreach ($json2['outboundOptions']['flights']as $theentity) {
$result[] = $theentity['flightNumber'];
}
print_r($result);
The code above return me a error, "Invalid argument supplied for foreach()".I searched around, but still have not found the solution yet..
It is giving you that error because outboundOptions is an array of objects. What you want is to access the first object:
foreach ($json2['outboundOptions'][0]['flights']as $theentity) {
$result[] = $theentity['flightNumber'];
}
Also, remove the trailing comma (,) from your ] at the end as that causes invalid json.
You can check if your json is valid by going to jsonlint.com
Working Example
Update as per your comment
To get all the flights, change your foreach loop to this:
foreach ($json3['outboundOptions'] as $flight) {
foreach($flight['flights'] as $theentity) {
$result[] = $theentity['flightNumber'];
}
}
Example
remove the trailing ',' near the very end of your json.
change your code, add a [0] before ['flights']
$json2 = json_decode($json,TRUE);
$result= array();
foreach ($json2['outboundOptions'][0]['flights']as $theentity) {
$result[] = $theentity['flightNumber'];
}
print_r($result);