change "0" to names in Json file - php

I am using PHP array and outputing to JSON string. I want to convert "0" in the json format to lets say calling them "items". Since while importing this to oracle db it says expecting names instead of zero. When I change the index ( 0, 1, 2 ) to be called just items, it works normally.
Here is the PHP array, and I am outputting it as json.
$data = array(
'INDIVIDUAL_SALUTATION' => $salution,
'INDIVIDUAL_FIRST_NAME' => $firstname,
'INDIVIDUAL_LAST_NAME' => $lastname,
'GENDER' => $gender,
'DATE_OF_BIRTH' => $result['Birthday'],
'EMAIL_ID' => $result['Email'],
'MOBILE_NUMBER' =>$result['Phone'],
'MOBILE_COUNTRY_CODE' => substr($result['Phone'], 1, 3),
'OCCUPATION' => null,
'OCCUPATION_STATUS' => null,
'ADDRESS_LINE1' => $result['Address_street'],
'TOWN' => $result['Address_city'],
'POSTAL_CODE' => $result['Address_zip'],
'COUNTRY' => $result['country_name'],
'CUSTOMER_NUMBER' => $result['Owner'],
'POLICY_START_DATE' => $result['paid_thru_date'],
'POLICY_END_DATE' => $result['duedate'],
'LOAN_AGREEMENT_NUMBER' => $result['ORIG_ID'],
'REPAYABLE_AMOUNT' => $result['repayable_amount'],
'FINANCE_TERM_MONTHS' => $result['finance_term_months'],
'MONTHLY_INSTALLMENT' => $result['monthly_installment'],
'AMOUNT_INSURED' => $result['amount_insured'],
'CURRENCY_ID' => $result['Abbreviation']
);
$jsonArray[] = $data;
}
$mainInfo = array(
'SRC_NAME' => 'AEX',
"RUN_NUMBER" => 1,
"RUN_DATE" => date("Ymd"),
"RUN_NO_OF_RECORDS" => $arrayCount,
"YTD_NO_OF_RECORDS" => $arrayCount
);
$finalArray = array_merge($jsonArray , $mainInfo);
$this->output->set_content_type('application/json');
$this->output->set_output(json_encode($finalArray));
$this->output->set_content_type('application/json');
$this->output->set_output(json_encode($mainInfo));
Here is the output
{
"0":{
"INDIVIDUAL_SALUTATION":"MR",
"INDIVIDUAL_FIRST_NAME":"borrower",
"INDIVIDUAL_LAST_NAME":"three",
"GENDER":"M",
"DATE_OF_BIRTH":"1993-09-17",
"EMAIL_ID":"borrowerthree#aurorax.co",
"MOBILE_NUMBER":"+3581466144569",
"MOBILE_COUNTRY_CODE":"358",
"OCCUPATION":null,
"OCCUPATION_STATUS":null,
"ADDRESS_LINE1":"Vaskivuorentie 22B",
"TOWN":"Vantaa",
"POSTAL_CODE":"01600",
"COUNTRY":"Finland",
"CUSTOMER_NUMBER":"772",
"POLICY_START_DATE":"2017-01-02",
"POLICY_END_DATE":"2017-07-01",
"LOAN_AGREEMENT_NUMBER":"7",
"REPAYABLE_AMOUNT":"50.42",
"FINANCE_TERM_MONTHS":"6",
"MONTHLY_INSTALLMENT":"8.40",
"AMOUNT_INSURED":"50.42",
"CURRENCY_ID":"EUR"
},
"1":{
"INDIVIDUAL_SALUTATION":"MR",
"INDIVIDUAL_FIRST_NAME":"borrower",
"INDIVIDUAL_LAST_NAME":"three",
"GENDER":"M",
"DATE_OF_BIRTH":"1993-09-17",
"EMAIL_ID":"borrowerthree#aurorax.co",
"MOBILE_NUMBER":"+3581466144569",
"MOBILE_COUNTRY_CODE":"358",
"OCCUPATION":null,
"OCCUPATION_STATUS":null,
"ADDRESS_LINE1":"Vaskivuorentie 22B",
"TOWN":"Vantaa",
"POSTAL_CODE":"01600",
"COUNTRY":"Finland",
"CUSTOMER_NUMBER":"772",
"POLICY_START_DATE":"2017-01-02",
"POLICY_END_DATE":"2017-07-01",
"LOAN_AGREEMENT_NUMBER":"9",
"REPAYABLE_AMOUNT":"40.35",
"FINANCE_TERM_MONTHS":"6",
"MONTHLY_INSTALLMENT":"6.73",
"AMOUNT_INSURED":"40.35",
"CURRENCY_ID":"EUR"
},
"2":{
"INDIVIDUAL_SALUTATION":"MR",
"INDIVIDUAL_FIRST_NAME":"borrower",
"INDIVIDUAL_LAST_NAME":"two",
"GENDER":"M",
"DATE_OF_BIRTH":"1993-09-17",
"EMAIL_ID":"borrowertwo#aurorax.co",
"MOBILE_NUMBER":"+358466144569123",
"MOBILE_COUNTRY_CODE":"358",
"OCCUPATION":null,
"OCCUPATION_STATUS":null,
"ADDRESS_LINE1":"Vaskivuorentie 22B",
"TOWN":"Vantaa",
"POSTAL_CODE":"01600",
"COUNTRY":"Finland",
"CUSTOMER_NUMBER":"770",
"POLICY_START_DATE":"2017-01-02",
"POLICY_END_DATE":"2017-07-01",
"LOAN_AGREEMENT_NUMBER":"11",
"REPAYABLE_AMOUNT":"99.84",
"FINANCE_TERM_MONTHS":"6",
"MONTHLY_INSTALLMENT":"16.64",
"AMOUNT_INSURED":"99.84",
"CURRENCY_ID":"EUR"
},
"RUN_NUMBER":1,
"RUN_DATE":"20170109"
}
What I am trying to do is make it look like instead of 0 have 'items' : {} and then move on, so I can import it to oracle.
How can I achieve this with php?

Don't use array_merge, put the array in an element of $mainInfo:
$mainInfo['items'] = $jsonArray;
$this->output->set_output(json_encode($mainInfo));

Create index variable and make it to zero
$index = 0
And change this $jsonArray[] = $data; to this $jsonArray['item' .$index++] = $data;
Hope that helps

Related

PHP array to JSON encoded string

I want JSON in below format, from PHP array,
How should I write PHP array and How should I convert it to JSON to get specific output in below format
{
"value": [
"01GQSE92030S8MNA78WQZ09JJQ",
"{\n\"user_id\": \"{{current_user.id}}\",\n\"user_phone\": \"{{current_user.phone}}\",\n\"ticket_id\": \"{{ticket.id}}\",\n\"ticket_comment\": \"{{ticket.latest_comment}}\",\n\"ticket_comment_author\": \"{{ticket.latest_comment.author.name}}\",\n\"organization_id\": \"{{ticket.organization.external_id}}\",\n\"organization_name\": \"{{ticket.organization.name}}\",\n\"requester_name\": \"{{ticket.requester.name}}\",\n\"requester_phone\": \"{{ticket.requester.phone}}\"\n}"
]
}
I tried below PHP array with json_encode, but output is not in required format,
array(
"value" => "01GQSE92030S8MNA78WQZ09JJQ",
array(
"user_id" => "{{current_user.id}}",
"user_phone" => "{{current_user.phone}}",
"ticket_id" => "{{ticket.id}}",
"ticket_comment" => "{{ticket.latest_comment}}",
"ticket_comment_author" => "{{ticket.latest_comment.author.name}}",
"organization_id" => "{{ticket.organization.external_id}}",
"organization_name" => "{{ticket.organization.name}}",
"requester_name" => "{{ticket.requester.name}}",
"requester_phone" => "{{ticket.requester.phone}}",
"agent_external_id" => "{{current_user.external_id}}",
"ticket_external_id" => "{{ticket.external_id}}",
"customer_external_id" => "{{ticket.requester.external_id}}"
)
);
You need to encode the second entry array to JSON, also in your desired output is need to show the \n, so add second parameter JSON_PRETTY_PRINT in json_encode here is the code.
<?php
$array = [
"value" => [
"01GQSE92030S8MNA78WQZ09JJQ",
json_encode([
"user_id" => "{{current_user.id}}",
"user_phone" => "{{current_user.phone}}",
"ticket_id" => "{{ticket.id}}",
"ticket_comment" => "{{ticket.latest_comment}}",
"ticket_comment_author" => "{{ticket.latest_comment.author.name}}",
"organization_id" => "{{ticket.organization.external_id}}",
"organization_name" => "{{ticket.organization.name}}",
"requester_name" => "{{ticket.requester.name}}",
"requester_phone" => "{{ticket.requester.phone}}",
"agent_external_id" => "{{current_user.external_id}}",
"ticket_external_id" => "{{ticket.external_id}}",
"customer_external_id" => "{{ticket.requester.external_id}}",
],JSON_PRETTY_PRINT),
],
];
print_r(json_encode($array,JSON_PRETTY_PRINT));
Here the live example : https://onlinephp.io/c/9efee

PHP json array manipulation

I have a JSON array like this:
{
result:{
customers:[
{
customer_id:16096,
customer_name:"test#test.test",
customer_login_name:"******",
customer_login_pwd:"*****",
customer_active:0,
customer_register_date:"2018-07-20 10:48:22",
customer_dashboard_email:"******",
customer_dashboard_pwd:"******",
used:"0.00",
name:"Trial",
price:0,
bandwidth:1,
start_date:"2018-07-20",
end_date:"2018-07-27",
package_is_active:1
},
{
customer_id:16648,
customer_name:"asd#asd.asd",
customer_login_name:"******",
customer_login_pwd:"********",
customer_active:1,
customer_register_date:"2018-08-08 17:24:16",
customer_dashboard_email:"******#*******.com",
customer_dashboard_pwd:"******",
used:"0.00",
name:"Trial",
price:0,
bandwidth:1,
start_date:"2018-08-08",
end_date:"2018-08-15",
package_is_active:1
},
{
customer_id:15271,
customer_name:"MarioRossiTEST",
customer_login_name:"mario#test.test",
customer_login_pwd:"*****",
customer_active:0,
customer_register_date:"2018-06-22 11:36:42",
customer_dashboard_email:"*****#******.com",
customer_dashboard_pwd:"*******",
used:"0.00",
name:"Trial",
price:0,
bandwidth:1,
start_date:"2018-06-22",
end_date:"2018-06-30",
package_is_active:0
},
]
}
}
Now in PHP i would like to provide the "customer_name" and retreive the "customer_id" of the same customer.
For example i provide "test#test.test" and i would like to get "16096".
Any way i could do this?
EDIT: After decoding the JSON array to PHP:
If you are doing this very often, I would suggest for looping through the array and creating a dictionary with the "customer_name" value as the key and the "customer_id", "customer_login_name", etc. in a dictionary that's the value to the "customer_name" key.
$customers_dic = {
"test#test.test"=> {
customer_id => 16096,
customer_login_name => "******",
customer_login_pwd =>"*****",
customer_active => 0,
customer_register_date => "2018-07-20 10:48:22",
customer_dashboard_email => "******",
customer_dashboard_pwd => "******",
used => "0.00",
name => "Trial",
price => 0,
bandwidth => 1,
start_date => "2018-07-20",
end_date => "2018-07-27",
package_is_active => 1
},
"asd#asd.asd" => {
customer_id => 16648,
customer_login_name => "******",
customer_login_pwd => "********",
customer_active => 1,
customer_register_date => "2018-08-08 17:24:16",
customer_dashboard_email => "******#*******.com",
customer_dashboard_pwd => "******",
used => "0.00",
name => "Trial",
price => 0,
bandwidth => 1,
start_date => "2018-08-08",
end_date => "2018-08-15",
package_is_active => 1
},
"mario#test.test" => {
customer_id => 15271,
customer_name => "MarioRossiTEST",
customer_login_pwd => "*****",
customer_active => 0,
customer_register_date => "2018-06-22 11:36:42",
customer_dashboard_email => "*****#******.com",
customer_dashboard_pwd => "*******",
used => "0.00",
name => "Trial",
price => 0,
bandwidth => 1,
start_date => "2018-06-22",
end_date => "2018-06-30",
package_is_active => 0
},
}
This way you can quickly access any "customer_id" by going $customers_dic["some#customer.name"]["customer_id"].
If you are just doing this a small number of times, you can just for loop through the customers array, keeping track of the index and checking if you have arrived on the desired customer's name.
$desired_customer_id;
for ($i = 0; $i < count($customers); $i++) {
if ($customers[$i]["customer_name"] === $desired_customer_name) {
$desired_customer_id = $customers[$i]["customer_id"];
}
}
You could also do this with a foreach instead; choice is up to you. :)
http://php.net/manual/en/function.json-decode.php
$arr = json_decode($json, true);
then you need to find your customer
array_filter($arr['result']['customers'], function ($customer) {
return ($customer['customer_name'] === 'test#test.test')
});
http://php.net/manual/en/function.array-filter.php

MongoDb aggregate error "each element of the 'pipeline' array must be an object"

Here is my aggregation code for mongodb collection :
$mongo_db_name = "db_".$tenant_id;
$con = new MongoClient($this->config->item('mongo_instance'));
$db = $con->$mongo_db_name;
$collection = $db->$module;
$options = array('cursor' => array("batchSize" => 4 ));
$pipeline=array(
array('$match'=>array('deleted'=>'0')),
array('$group'=>array('_id' => array('id'=>'$id', 'accountnm' => '$account_name', 'legal___corporate_name_cstm' => '$legal___corporate_name_cstm', 'funded_by_cstm' => '$funded_by_cstm', 'approval_amount_cstm' => '$approval_amount_cstm', 'payback_amount_cstm' => '$payback_amount_cstm', 'factor_rate_cstm' => '$factor_rate_cstm', 'daily_ach_amount__1_cstm' => '$daily_ach_amount__1_cstm', 'total_commission_owed_cstm' => '$total_commission_owed_cstm', 'total_commission_paid_cstm' => '$total_commission_paid_cstm', 'upfront_amount_due_cstm' => '$upfront_amount_due_cstm', 'upfront_amount_due_date_cstm' => '$upfront_amount_due_date_cstm', 'date_modified' => '$date_modified'))),
);
$data = $collection->aggregate($pipeline,$options);
var_dump($data);
I am getting this error with the above code
array (size=4) 'ok' => float 0 'errmsg' => string 'Each element of
the 'pipeline' array must be an object' (length=54) 'code' => int 14
'codeName' => string 'TypeMismatch' (length=12)
If I try to encode the pipeline using json_encode the result is 'null'.
If I use find(array('deleted'=>'0')); it returns all documents as expected.
Can anyone help me about where I am going wrong or whatmust I do to resolve this ?
aggregation pipeline takes objects in array so your pipeline should be like
[
{$match:{}};
{$group:{}};
{$somepipelinestageOperator:{}}
]
but if you have pipeline with array as tages and not object you will get above error(each element of pipeline must be an array..).
[
[$match:{}],
[$group:{}],
[$somepipelinestageOperator:{}]
]
in your code there are array for match and group so its failing.
$pipeline=array(
array('$match'=>array('deleted'=>'0')),
array('$group'=>array('_id' => array('id'=>'$id', 'accountnm' => '$account_name', 'legal___corporate_name_cstm' => '$legal___corporate_name_cstm', 'funded_by_cstm' => '$funded_by_cstm', 'approval_amount_cstm' => '$approval_amount_cstm', 'payback_amount_cstm' => '$payback_amount_cstm', 'factor_rate_cstm' => '$factor_rate_cstm', 'daily_ach_amount__1_cstm' => '$daily_ach_amount__1_cstm', 'total_commission_owed_cstm' => '$total_commission_owed_cstm', 'total_commission_paid_cstm' => '$total_commission_paid_cstm', 'upfront_amount_due_cstm' => '$upfront_amount_due_cstm', 'upfront_amount_due_date_cstm' => '$upfront_amount_due_date_cstm', 'date_modified' => '$date_modified'))),
);
you can print your pipeline and see that your pipeline stages are having array and not object.

PHP var_export - elgg_get_entities

I am trying to create an API for the social network Elgg. It's working but I am very puzzled by some results.
This is my API:
function my_get_group() {
$group=elgg_get_entities(array(
types => 'group',
guid=>75,
));
return var_export($group[0], true);
}
and this is the reult
{
status: 0
result: "ElggGroup::__set_state(array( 'url_override' => NULL, 'icon_override' => NULL, 'temp_metadata' => array ( ), 'temp_annotations' => array ( ), 'temp_private_settings' => array ( ), 'volatile' => array ( ), 'tables_split' => 2, 'tables_loaded' => 2, 'attributes' => array ( 'guid' => 75, 'type' => 'group', 'subtype' => 0, 'owner_guid' => 54, 'site_guid' => 1, 'container_guid' => 54, 'access_id' => 2, 'time_created' => 1442385556, 'time_updated' => 1442385557, 'last_action' => 1442455132, 'enabled' => 'yes', 'name' => 'goup1', 'description' => '<p>description1</p>', ), 'valid' => false, ))"}
So far so good.
I can now modify my APIto get only the description, by changing
//return var_export($group[0], true);
return var_export($group[0]->description, true);
which gives me
{
status: 0
result: "'<p>description1</p>'"
}
Now the part that I don't understand is the following. if I modify my code to:
//return var_export($group[0], true);
return var_export($group[0]->briefdescription, true);
I get
{
status: 0
result: "'brief description1'"
}
Can someone explain me where this data comes from? I cannot see any mention of briefdescription when I run
return var_export($group[0], true);
Thanks for your help
bonododo
All of those values come through PHP magic methods __get and __set. The reason you see description in var_export result is that it's an attribute, the briefdescription is a metadata.
Have a look at documentation, especially:
Data model overview
Metadata section
ElggGroup-specific attributes

Displaying one string from a list of multiple strings

I'm trying to grab data from this array, but when I do var_dump($ArrayedLevels['Attack']); it returns NULL, I know for a fact that it was able to grab the data from the SQL database, I think it has something to do with my array. Any help would be greatly appreciated.
include("highscoresconfig.php");
$GrabXP = $database2->prepare("SELECT * FROM `skills` WHERE `playerName` = ?");
$GrabXP->execute(array($playerName));
$MainResult = $GrabXP->fetchAll();
$ArrayedLevels = $array = [
"Attack" => $MainResult['Attacklvl'],
"Defence" => $MainResult['Defencelvl'],
"Strength" => $MainResult['Strengthlvl'],
"Hitpoints" => $MainResult['Hitpointslvl'],
"Ranged" => $MainResult['Rangelvl'],
"Prayer" => $MainResult['Prayerlvl'],
"Magic" => $MainResult['Magiclvl'],
"Cooking" => $MainResult['Cookinglvl'],
"Woodcutting" => $MainResult['Woodcuttinglvl'],
"Fletching" => $MainResult['Fletchinglvl'],
"Fishing" => $MainResult['Fishinglvl'],
"Firemaking" => $MainResult['Firemakinglvl'],
"Crafting" => $MainResult['Craftinglvl'],
"Smithing" => $MainResult['Smithinglvl'],
"Mining" => $MainResult['Mininglvl'],
"Herblore" => $MainResult['Herblorelvl'],
"Agility" => $MainResult['Agilitylvl'],
"Thieving" => $MainResult['Thievinglvl'],
"Slayer" => $MainResult['Slayerlvl'],
"Farming" => $MainResult['Farminglvl'],
"Runecrafting" => $MainResult['Runecraftlvl'],
"Hunter" => $MainResult['Hunterlvl'],
"Construction" => $MainResult['Constructionlvl'],
"Summoning" => $MainResult['Summoninglvl'],
"Dungeoneering" => $MainResult['Dungeoneeringlvl'],
];
var_dump($ArrayedLevels["Attack"]);
Problem might be because the fetchAll() returns all the rows of your query.
if($GrabXP->execute(array($playerName))){
//Success
$MainResult = $GrabXP->fetchAll();
/*
This will give you all the rows. Use a foreach loop to iterate through all the rows.
If you want only the first row, add this-
*/
$MainResult = $MainResult[0];
//The rest of your code.
$ArrayedLevels = $array = Array(
"Attack" => $MainResult['Attacklvl'],
...
);
var_dump($ArrayedLevels["Attack"]);
}
else{
//Failure
}
The brackets don't work in PHP when creating a new array, use array() to create one.
Actually: as of PHP 5.4 they do work, see here: http://nl3.php.net/manual/en/language.types.array.php
Try var_dump($MainResult);
if all good, try create your array like this:
$ArrayedLevels = array(
"Attack" => $MainResult['Attacklvl'],
"Defence" => $MainResult['Defencelvl'],
"Strength" => $MainResult['Strengthlvl'],
"Hitpoints" => $MainResult['Hitpointslvl'],
"Ranged" => $MainResult['Rangelvl'],
"Prayer" => $MainResult['Prayerlvl'],
"Magic" => $MainResult['Magiclvl'],
"Cooking" => $MainResult['Cookinglvl'],
"Woodcutting" => $MainResult['Woodcuttinglvl'],
"Fletching" => $MainResult['Fletchinglvl'],
"Fishing" => $MainResult['Fishinglvl'],
"Firemaking" => $MainResult['Firemakinglvl'],
"Crafting" => $MainResult['Craftinglvl'],
"Smithing" => $MainResult['Smithinglvl'],
"Mining" => $MainResult['Mininglvl'],
"Herblore" => $MainResult['Herblorelvl'],
"Agility" => $MainResult['Agilitylvl'],
"Thieving" => $MainResult['Thievinglvl'],
"Slayer" => $MainResult['Slayerlvl'],
"Farming" => $MainResult['Farminglvl'],
"Runecrafting" => $MainResult['Runecraftlvl'],
"Hunter" => $MainResult['Hunterlvl'],
"Construction" => $MainResult['Constructionlvl'],
"Summoning" => $MainResult['Summoninglvl'],
"Dungeoneering" => $MainResult['Dungeoneeringlvl'],
);
first of all try to print the structure of the variable $MainResult:
var_dump($MainResult);
FetchAll return an array with all restuls like
resutl = [
[0] => ['first row'],
[1] => ['sec. row']
]
you will See The variable $MainResult looks like:
MailResult => [
[0] => ['Attacklvl' => 'foo'],
[1] => ['Defencelvl' => 'bar']
]

Categories