i need help
I have data that comes from a database and gets in a table and with this data I would like to create a json file, here is the structure of my table :
Array
(
[TSHIMAMBU KAFIMBA JEAN] => Array
(
[0] => Array
(
[TAMBWE MANANGA JOSEPH] => Array
(
[0] => Array
(
[MBALA SHABANI JEAN PAUL] =>
)
[1] => Array
(
[MUSANGU KYULU BENOIT] => Array
(
[0] => Array
(
[MBUYI MUKADI ROGER] =>
)
)
)
[2] => Array
(
[MUTOMBO KOLOMONI FRANCOIS] =>
)
[3] => Array
(
[SUNGUNRA MATUNDA ELISÉE] =>
)
)
)
[1] => Array
(
[NDAY WA NDAY DAVID] => Array
(
[0] => Array
(
[LUBINDA BANZA JACQUIE] =>
)
)
)
)
)
and here is the code that helps me get this table
function myfunction($parent_id, $departement_id){
$tab = fetchchildren($parent_id, $departement_id);
$departement_database = new DepartementDatabase();
$employees = $departement_database->show_employes_of_departement($departement_id);
$name_parent = " ";
foreach ($employees as $employee){
if($employee['id'] == $parent_id){
$name_parent = utf8_encode($employee['name_employee']);
break;
}
}
$tab2 = array();
foreach ($tab as $value){
$tab2[$name_parent][] = myfunction($value['id'], $departement_id);
}
if (count($tab) == 0){
$tab2[$name_parent] = null;
}
return $tab2;
}
$tab = myfunction(1, 1);
how to browse my array to get this json format ????
here is the json format i want to have
[{
"label": "President",
"name": "John Doe",
"children": [{
"name" : "Jane Smith",
"label": "Vice President of Administration",
"children": [{
"name": "Peter West",
"label": "Director of Finance"
}, {
"name" : "Sarah Jones",
"label": "Director of Human Resources"
}]
}, {
"name" : "Richard Easton",
"label": "Vice President of Operations",
"children": [{
"name" : "Amy Thomas",
"label": "Director of Distribution"
}, {
"name" : "Greg Li",
"label": "Director of Customer Service",
"children": [{
"name" : "Laronda Phillips",
"label": "Technical Support Manager"
}]
}]
}, {
"name" : "Alice Ozaltin",
"label": "Vice President of Merchandising",
"children": [{
"name": "Zach Kwon",
"label": "Director of Purchasing",
"children": [
{
"name": "Jonathan Branham",
"label": "Internal Purchasing Manager"}]
}, {
"name": "Elizabeth Norman",
"label": "Director of Appliances"
}, {
"name" : "Peter Stevens",
"label": "Director of Clothing",
"children": [{
"name": "Rebecca Hammond",
"label": "Womens Clothing Planner"
}, {
"name": "Alex Kaplan",
"label": "Mens Clothing Planner"
}]
}, {
"name" : "Mark Hughes",
"label": "Product Information Coordinator"
}, {
"name" : "Elvis Presley",
"label": "Producteur Musical"
}]
}, {
"name" : "Diego KAO",
"label": "Vice President of Merchandising",
"children": [{
"name": "Zach Kwon",
"label": "Director of Purchasing",
"children": [
{
"name": "Jonathan Branham",
"label": "Internal Purchasing Manager"}]
}, {
"name": "Elizabeth Norman",
"label": "Director of Appliances"
}, {
"name" : "Peter Stevens",
"label": "Director of Clothing",
"children": [{
"name": "Rebecca Hammond",
"label": "Womens Clothing Planner"
}, {
"name": "Alex Kaplan",
"label": "Mens Clothing Planner"
}]
}, {
"name" : "Mark Hughes",
"label": "Product Information Coordinator"
}, {
"name" : "Elvis Presley",
"label": "Producteur Musical"
}]
}]
}]
Need for help please, thanks
i found out how to do it with nested loops. thank you for your attention
Related
I have fetch value from database and returning its array in json format. This is my code to get values. First array is working fine. But i need to add static array after every index in array. This is my code
$value = $this->TestModel->get_user_details($userIds);
this function returns array in json format e.g.
[
{
"user_id": "1",
"name": "test 1",
},
{
"user_id": "2",
"name": "test 2",
},
{
"user_id": "3",
"name": "test 3",
},
]
now i need to add below static json array with every item of array. This is e.g
$test1= array("student_list"=> array(array("stu_id"=>1, "name"=> "abc") , array("stu_id"=>2, "name"=> "xyz")),
"class"=> "12th",
"average_score"=>"5",
"results"=>array(array("result_date"=>"2012-12-13","city"=>"city 1"),array("result_date"=>"2015-10-13","city"=>"city 2")));
I have tried it with array_push and array_merge but it add this at the end end of array.
I need this Response
[
{
"user_id": "1",
"name": "test 1",
"student_list": [
{
"stu_id": 1,
"name": "abc",
},
{
"stu_id": 2,
"name": "xyz",
}
],
"class": "12th",
"average_score": "5",
"results": [
{
"result_date": "2012-12-13",
"city": "City 1",
},
{
"result_date": "2012-10-13",
"city": "City 2",
}
]
},
{
"user_id": "2",
"name": "test 2",
"student_list": [
{
"stu_id": 3,
"name": "asd",
},
{
"stu_id": 4,
"name": "ghj",
}
],
"class": "10th",
"average_score": "5",
"results": [
{
"result_date": "2011-12-13",
"city": "City 3",
},
{
"result_date": "2011-10-13",
"city": "City 4",
}
]
},
]
If you want to add $test1 to to every element you your array you should merge each element, like so:
$value = $this->TestModel->get_user_details($userIds);
$test1 = array(
"student_list" => array(array("stu_id" => 1, "name" => "abc"), array("stu_id" => 2, "name" => "xyz")),
"class" => "12th",
"average_score" => "5",
"results" => array(array("result_date" => "2012-12-13", "city" => "city 1"), array("result_date" => "2015-10-13", "city" => "city 2"))
);
$decoded = json_decode($value, true);
for ($i = 0; $i < count($decoded); $i++) {
$decoded[$i] = array_merge($decoded[$i], $test1);
}
$value = json_encode($decoded);
I am trying to add a customer(Podio item) to my Podio app. This customer is being added programmatically from within a php application. There are several fields present on the customer: Name, Address, Email, Title, Phone Number, and an array of Tags. When a tag is added the color changes to highlight it.
In previous iterations I have been successful adding a different tag(newsletter_subscribed) using the ID of the tag value that I want highlighted. Now when I try to add another tag(hospital, clinic, or urgent_care) it is throwing a PodioBadRequestError. The error cited is that the ID being used is and invalid type(integer).
I got the values of the tag ID's by looking at the JSON returned when an existing customer created manually within my Podio customer application. When I look at the ID fields in the JSON they are most definitely integers, I have tried strings as well. Everything I try throws the 400 Bad Request on the ID that I am trying to add.
I cannot for the life of me figure out why it is throwing the error when I add the tag ID's.
Below is the way that the application is put together:
This is the code that builds and sends the request:
public function addToPodio()
{
$address = $this->Address . ", " .
$this->Address2 . ", " .
$this->City . ", " .
$this->State . " " .
$this->Zip;
$item = [
'fields' => [
'name' => $this->PrimaryContactFirstName,
'last-name' => $this->PrimaryContactLastName,
'email-address' => ['type' => 'work', 'value' => $this->PrimaryContactEmail],
'phone-number' => ['type' => 'work', 'value' => $this->PrimaryContactPhone],
'address' => $address,
'organization' => [$this->CompanyName],
'tags-2' => []
],
];
if ($this->Newsletter && defined('PODIO_NEWSLETTER_TAG_ID')){
$item['fields']['tags-2'][] = PODIO_NEWSLETTER_TAG_ID;
}
if($this->OrganizationType && defined('PODIO_ORGANIZATION_TYPE_ID')){
if($this->OrganizationType == "Clinic"){
$item['fields']['tags-2'][] = PODIO_ORGANIZATION_TYPE_CLINIC_TAG_ID;
}
else if($this->OrganizationType == "Hospital"){
$item['fields']['tags-2'][] = PODIO_ORGANIZATION_TYPE_HOSPITAL_TAG_ID;
}
try {
//This is where the request is being made
$customer = PodioItem::create(PODIO_CUSTOMER_APP_ID, $item);
$this->PodioId = $customer->item_id;
$this->write();
} catch (Exception $e) {
error_log('We encountered an error adding your item to Podio' . $e);
return 'An error occurred while updating Podio. Please try again. If the error...';
}
This is the PHP $item that is being passed to the request that gets sent to the Podio API:
Array
(
[fields] => Array
(
[name] => Joe
[last-name] => Test
[phone-number] => Array
(
[type] => work
[value] => 8675309
)
[address] => 123 Main Road, , East Test, NY 12345
[organization] => Array
(
[0] => Another Test
)
[tags-2] => Array
(
[0] => 16
[1] => 96
)
)
)
This is the config file with the all of the constants, secrets tokens and ID's needed to connect to the Podio API, authenticate and all of that stuff. Obfuscated Example below:
define('PODIO_CUSTOMER_APP_ID', 'xxxxx-obfuscated-xxxxx');
define('PODIO_CUSTOMER_APP_TOKEN', 'xxxxx-obfuscated-xxxxx');
define('PODIO_CLIENT_SECRET', 'xxxxx-obfuscated-xxxxx');
define('PODIO_CLIENT_ID', 'xxxxx-obfuscated-xxxxx');
define('PODIO_ORGANIZATION_TYPE_ID', 'xxxxx-obfuscated-xxxx');
define('PODIO_NEWSLETTER_TAG_ID', 'xxxxx-obfuscated-xxxxx');
define('PODIO_ORGANIZATION_TYPE_CLINIC_TAG_ID', 'xxxxx-obfuscated-xxxxx');
Podio::setup(PODIO_CLIENT_ID, PODIO_CLIENT_SECRET, [
'session_manager' => Injector::inst()->get(PodioSession::class),
'curl_options' => array(),
]);
Below is the JSON that I used to get the values of the ID's. I got this from a postman request to the API. The basic form of the request without all of the authentication present looked like:
podio.com/MY_PODIO_ACCOUNT_NAME/app/APPLICATION_ID/item/ITEM_ID
Please note: I removed many of the main fields like Address and Organization for brevity's sake, so it won't match completely the PHP request object above.
{
"id": 0000,
"item_id": 00000,
"revision": 0,
"app": null,
"app_item_id": 00000,
"app_item_id_formatted": "PODIO_Field_ID:00000",
"external_id": null,
"title": "TEST ITEM",
"fields": [
{
"id": 0000,
"field_id": 0000,
"type": "text",
"external_id": "name",
"label": "First Name",
"values": [
{
"value": "Joe"
}
],
"config": {
"settings": {
"format": "plain",
"size": "small"
},
"mapping": "contact_name",
"label": "First Name"
},
"humanized_value": "Joe"
},
{
"id": 0000,
"field_id": 0000,
"type": "text",
"external_id": "last-name",
"label": "Last Name",
"values": [
{
"value": "<p>Test<br /></p>"
}
],
"config": {
"settings": {
"format": "html",
"size": "large"
},
"mapping": null,
"label": "Last Name"
},
"humanized_value": "Test"
},
{
"id": 0000,
"field_id": 0000,
"type": "phone",
"external_id": "phone-number",
"label": "Phone Number",
"values": [
{
"type": "work",
"value": "867-5309"
}
],
"config": {
"settings": {
"call_link_scheme": "callto",
"possible_types": [
"mobile",
"work",
"home",
"main",
"work_fax",
"private_fax",
"other"
]
},
"mapping": "contact_phone",
"label": "Phone Number"
},
"humanized_value": "8675309"
},
{
"id": 11111,
"field_id": 11111,
"type": "category",
"external_id": "tags-2",
"label": "Tags",
"values": [
{
"value": {
"status": "active",
"text": "Clinic",
"id": 16,
"color": "DCEBD8"
}
},
{
"value": {
"status": "active",
"text": "Newlsetter_subscribed",
"id": 96,
"color": "DCEBD8"
}
}
],
"config": {
"settings": {
"multiple": true,
"options": [
{
"status": "active",
"text": "Mktng:test1/2020",
"id": 150,
"color": "DCEBD8"
},
{
"status": "active",
"text": "Mktng:Test2/2020",
"id": 3,
"color": "DCEBD8"
},
{
"status": "active",
"text": "SampleTest",
"id": 48,
"color": "DCEBD8"
},
{
"status": "deleted",
"text": "Test Center",
"id": 139,
"color": "DCEBD8"
},
{
"status": "deleted",
"text": "Sample Center",
"id": 99,
"color": "DCEBD8"
},
{
"status": "deleted",
"text": "Testing Center",
"id": 140,
"color": "DCEBD8"
}
],
"display": "inline"
},
"mapping": null,
"label": "Tags"
},
"humanized_value": "Clinic; Newsletter;"
}
this JSON continues for pages and pages, I only included the relevant fields for my question.
It looks like the error is being thrown because of the organization value, not the tags value.
For a category field, an array of integer indices is correct.
[tags-2] => [ 16, 96 ]
For an app field, you need to provide an array of integer item ID's.
[organization] => [ 12345 ]
But your code above is sending an array of strings:
[organization] => [ "Another Test" ]
That won't work.
I have 4 table products, properties, property_items, property_product with relations like this
Product has many properties.
Property has many property_items.
Product has many property_items.
Property_product is intermediary table.
-- products --
Id name
1 Arrabiata
2 Bolognese
--properties --
Id name
1 Pasta type
2 Size
-- property_items --
Id name value property_id
1 Spinach spaghetti ..... 1
2 Linguine ..... 1
3 Spaghetti ..... 1
4 Small .... 2
5 Medium .... 2
6 Large ... 2
-- property_product --
product_id property_id property_item_id
1 1 1
1 1 2
1 2 4
1 2 6
2 1 2
2 1 3
2 2 5
I try use Gii to create those models with relations .
class Products extends \yii\db\ActiveRecord
{
//code
....
public function getProperties()
{
return $this->hasMany(Properties::className(), ['id' => 'property_id'])
->viaTable('property_product', ['product_id' => 'id']);
}
}
class Properties extends \yii\db\ActiveRecord
{
//code
...
public function getPropertyItems()
{
return $this->hasMany(PropertyItems::className(), ['property_id' => 'id']);
}
}
I want to query data with multi nested relation.
How can i create json response with below format in one active record query ?
[
{
"id": "1",
"name": "Arrabiata",
"properties": [
{
"id": "1",
"name": "Pasta type",
"property_items" : [
{
"id": "1",
"name": "Spinach spaghetti",
},
{
"id": "2",
"name": "Linguine",
},
]
},
{
"id": "2",
"name": "Size",
"property_items" : [
{
"id": "4",
"name": "Small",
},
{
"id": "6",
"name": "Large",
},
]
},
],
},
{
"id": "2",
"name": "Bolognese",
"properties": [
{
"id": "1",
"name": "Pasta type",
"property_items" : [
{
"id": "2",
"name": "Linguine",
},
{
"id": "3",
"name": "Spaghetti",
},
]
},
{
"id": "2",
"name": "Size",
"property_items" : [
{
"id": "5",
"name": "Medium",
},
]
},
]
}]
I use this query but it took too much perfomance
Menus::find()->with(['products' => function ($query) {
$query->with(['properties']);
}])
->where(['>', 'status', 0])
->andWhere(['resid' => $id])->asArray()->all();;
foreach ($menus as &$menu) {
foreach ($menu['products'] as &$product) {
foreach ($product['properties'] as &$property) {
$propertyItems = PropertyItems::find()->where(['property_id' => $property['id']]
)
->leftJoin('property_product', 'property_items.id = property_product.property_item_id')
->where(['property_product.product_id' => $product['id'],
'property_product.property_id' => $property['id']])
->asArray()->all();
$property['propertyItems'] = $propertyItems;
}
}
}
If I use this query
Menus::find()->with(['products' => function ($query) {
$query->with(['properties' => function ($query) {
$query->with(['propertyItems']);
}
]);
}
])->asArray()->all();
But the result not same as i expected because all property_items will show up in properties instead of depend on relating with products via table "property_product"
[
{
"id": "1",
"name": "Arrabiata",
"properties": [
{
"id": "1",
"name": "Pasta type",
"property_items" : [
{
"id": "1",
"name": "Spinach spaghetti",
},
{
"id": "2",
"name": "Linguine",
},
{
"id": "3",
"name": "Spaghetti",
},
]
},
{
"id": "2",
"name": "Size",
"property_items" : [
{
"id": "4",
"name": "Small",
},
{
"id": "6",
"name": "Large",
},
{
"id": "5",
"name": "Medium",
},
]
},
],
},
{
"id": "2",
"name": "Bolognese",
"properties": [
{
"id": "1",
"name": "Pasta type",
"property_items" : [
{
"id": "1",
"name": "Spinach spaghetti",
},
{
"id": "2",
"name": "Linguine",
},
{
"id": "3",
"name": "Spaghetti",
},
]
},
{
"id": "2",
"name": "Size",
"property_items" : [
{
"id": "4",
"name": "Small",
},
{
"id": "6",
"name": "Large",
},
{
"id": "5",
"name": "Medium",
},
]
}
]
}]
Thanks in advance.
You have to override the function fields() of the Products and Properties models.
for example:
class Products extends ActiveRecord {
function fields(){
return ['properties'];
}
}
class Properties extends ActiveRecord {
function fields(){
return ['property_items'];
}
}
I want JSON object as follows in that personal, address and itm have sequence of json object.
{
"id": "1",
"state": "12",
"personal": [
{
"name": "abc",
"contact":"1111111"
"address": [
{
"line1": "abc",
"city": "abc",
"itm": [
{
"num": 1,
"itm_detatils": {
"itemname": "bag",
"rate": 1000,
"discount": 0,
}
}
],
"status": "Y"
}
]
}
]
}
But I am getting result as follows in that I want json array at address and itm_details.
{
"id": "1",
"state": "12",
"personal": [
{
"name": "abc",
"contact": "1111111",
"address": {
"line1": "abc",
"city": "abc",
"itm": {
"inum": "1",
"itm_detatils": {
"itemname": "bag",
"rate": 1000,
"discount": 0
}
},
"status": "Y"
}
}
]
}
My PHP Code is as follow:
In that I am creating simple array and after that array inside array but during encoding to json it's not showing sequence of json object.
$a=array();
$a["id"]="1";
$a["state"]="12";
$a["personal"]=array();
$a["personal"][]=array(
"name"=>"abc",
"contact"=>"1111111",
"address"=>array(
"line1"=>"abc",
"city"=>"abc",
"itm"=>array(
"inum"=>"1",
"itm_detatils"=>array(
"itemname"=>"bag",
"rate"=>1000,
"discount"=>0,
),
),
"status"=>"Y",
),
);
echo json_encode($a);
Thanks in advance.
Add one more array
//...
"address" => array(
array(
"line1"=>"abc",
"city"=>"abc",
// ...
),
)
I 'm trying to make some pages with php and curl using REST API. I can connect application and get all values as JSON format with curl on PHP. But, I can not parse values what i want.
I used this PHP commands for decode json values ;
$data = json_decode($response, true);
print_r($data);
When I use this command i'm getting returning value like this ;
Array ( [links] => Array ( ) [content] => Array ( [0] => Array (
[#type] => ConsumerEnt [links] => Array ( [0] =>
Array ( [#type] => link [rel] => GET: Request [href] =>
http.....
) => Array ...etc
There are arrays inside arrays.. I could not find how to parse values i want. You can see values i want at following json codes;
Do you have any idea how it can be possible ?
Than
You can see Decoded JSON by http://json.parser.online.fr/
{
"links": [],
"content": [
{
"#type": "ConsumerEnt",
"links": [
{
"#type": "link",
"rel": "GET: Request",
"href": "https://ip/url"
},
{
"#type": "link",
"rel": "POST:Request",
"href": "https://ip/url"
}
],
"entitledOrg": [
{
"tRef": "local",
"tLabel": "local",
"sRef": "768882f2-cf89-4cc8-92b7",
"sLabel": "USsB01"
}
],
"citems": "a0221dfd-00f9-4019-95ed",
"name": "NAME I WANT TO GET",
"description": "Basic",
"isNoteworthy": false,
"dateCreated": "2016-09-25T11:44:02.698Z",
"lastUpdatedDate": "2016-09-25T12:46:45.474Z",
"iconId": "a0221dfd-00f9-4019-95ed-a74faeb2e1b2",
"catalogItemTypeRef": {
"id": "com.company",
"label": "Compo"
},
"serviceRef": {
"id": "7c92b9a5-9dd5-4819-9320-4127b1e3009d",
"label": "NAME I WANT TO GET"
},
"outputResourceRef": {
"id": "composition.type",
"label": "test"
}
},
{
"#type": "ConsumerEnti",
"links": [
{
"#type": "link",
"rel": "GET: Request",
"href": "https://ip/url"
},
{
"#type": "link",
"rel": "POST:Request",
"href": "https://ip/url"
}
],
"entitledOrg": [
{
"tRef": "local",
"tLabel": "local",
"sRef": "768882f2-cf89-4cc8-92b7",
"sLabel": "astDF1"
}
],
"catalogItemId": "89b43bcb-4b23-4fc0-af26-66bd5c6bd1bc",
"name": "NAME I WANT TO GET",
"description": "RASDhFASel",
"isNoteworthy": false,
"dateCreated": "2016-10-27T07:55:03.243Z",
"lastUpdatedDate": "2016-10-27T07:56:00.754Z",
"iconId": "compos.png",
"catalogItemTypeRef": {
"id": "com.company",
"label": "Compo"
},
"serviceRef": {
"id": "7c92b9a5-9dd5-4819-9320-4127b1e3009d",
"label": "NAME I WANT TO GET"
},
"outputResourceRef": {
"id": "composition",
"label": "Dep"
}
}
],
"metadata": {
"size": 20,
"totalElements": 2,
"totalPages": 1,
"number": 1,
"offset": 0
}
}
I guess i solved my issue like this ;
$data = json_decode($response, true);
print_r($data);
$j=count($data["content"]);
for ( $say=0 ; $say < $j ; $say++ )
{
print $data["content"][$say]["name"];
}
as a result i can list my products ;
Product1
Product2
Product3