PHP json array manipulation - php

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

Related

Elasticsearch index_options=docs for text data type does not return any search results

I have been using Elasticsearch 7.6 and PHP client API for all the operations.
I have created elasticsearch index settings and mappings as follows
$params = [
'index' => 'elasticindex',
'body' => [
'settings' => [
"number_of_shards" => 1,
"number_of_replicas" => 0,
"index.queries.cache.enabled" => false,
"index.soft_deletes.enabled" => false,
"index.requests.cache.enable" => false,
"index.refresh_interval" => -1
],
'mappings' => [
'_source' => [
"enabled" => false
],
'properties' => [
"text" => [
"type" => "text",
"index_options" => "docs"
]
]
]
]
];
I was able to index document using the following code
$params = array();
$params['index'] = 'elasticindex';
for($i = 1; $i <=2; $i++) {
$params['id'] = $i;
$params['body']['text'] = 'apple';
$responses = $client->index($params);
}
But when I use the following search query
$params = [
'index' => 'elasticindex',
'body' => [
'query' => [
'match' => [
"text" => "apple"
]
]
]
];
$results = $client->search($params);
I am getting empty results as follows
Array
(
[took] => 3
[timed_out] =>
[_shards] => Array
(
[total] => 1
[successful] => 1
[skipped] => 0
[failed] => 0
)
[hits] => Array
(
[total] => Array
(
[value] => 0
[relation] => eq
)
[max_score] =>
[hits] => Array
(
)
)
)
Without creating a static index template, if I try to index, elasticsearch dynamic mapping works well and I am getting the results.
The goal is that I want the elasticsearch to index only document id in its inverted index and not position or offset and I want to retrieve only matching document ids as results. Help is much appreciated. Thanks in advance!
Since the document is being returned by the get handler and not the query handler, your index is not being refreshed properly after indexing the document.
As you noted yourself, in your configuration you set:
"index.refresh_interval" => -1
.. which means that the index is not being refreshed automagically. There's seldom a need to change the refresh interval, except in very high throughput situations or where a particular behavior is wanted.
Try to index doc something like this.
$client = Elasticsearch\ClientBuilder::create()
->setHosts($hosts)
->build();
$params = [
'index' => 'elasticindex',
'type' => 'documents',
'id' => '1',
'body' => ['text' => 'apple']
];
$response = $client->index($params);
print_r($response);
Note: _id you can define dynamically if you want, else id will automatically set by elastic.
And try to get doc via a search query.
{
"query": {
"bool": {
"must": {
"term": {
"text": "apple"
}
}
}
}
}
If you want full-text search on this key, set this key property as
"properties": {
"name": {
"type": "text"
}
}

change "0" to names in Json file

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

Looping through an Multidimentinal/Associative Array

Looking for some help with looping through a multidimensional/associative array in PHP. Essentially, I need to loop through and output the certain key values in a table. Not having much luck.
Here is a sample of my array.
$myarray = array(
"body" => array(
"0" => array(
"machine" => array(
"id" => "1",
"name" => "macbookpro",
"description" => "laptop machine",
"state" => "reserved",
"state_since" => "2013-08-28 12:05:00",
"queue_snapshot" => array(
"time" => "2013-08-01 12:00:00",
"jobs" => "450",
"jobs_available" => "90",
"cputime_running" => "00:01:00",
"cputime_eligible" => "00:90:00",
"cputime_block" => " 90:00:00",
)
)
),
"1" => array(
"machine" => array(
"id" => "2",
"name" => "ipad",
"description" => "tablet machine",
"state" => "available",
"state_since" => "2013-08-28 12:05:00",
"queue_snapshot" => array(
"time" => "2013-08-01 12:00:00",
"jobs" => "50",
"jobs_available" => "20",
"cputime_running" => "00:05:00",
"cputime_eligible" => "00:12:00",
"cputime_block" => " 00:10:00",
)
)
)
));
I have some values in this array that will need to be accessed later so I only need to be able to access particular values in order to create this table. Needs to output like this....
Machine Name | Description | State | Jobs | Jobs Available |
macbookpro laptop machine reserved 450 90
ipad tablet machine available 50 20
Untestet on the fly
<?php
if(isset($myarray['body']) && is_array($myarray['body']))
foreach($myarray['body'] as $id=>$arr) {
$name = $arr['name'];
$description = $arr['description'];
$jobs = $arr['queue_snapshot']['jobs'];
$jobs_available = $arr['queue_snapshot']['jobs_available'];
echo "<br>$name $description $jobs $jobs_available";
}
?>

Adding Docusign Template array into REST Header

So I'm back again. My problem is this:
I have an array of Docusign Templates from checkboxes in a Codeigniter view:
<?php
echo form_open('create_envelope');
foreach ($response["envelopeTemplates"] as $envelopeTemplate) { ?>
<li><?php echo form_checkbox('templatearray[]', $envelopeTemplate["templateId"], FALSE), $envelopeTemplate["name"]; ?></li>
<?php } ?>
What I'm trying to do is add the templates to our REST Header request:
$data = array(
"accountId" => $accountId,
"emailSubject" => "Hello World!",
"emailBlurb" => "This comes from PHP",
"templateId" => "ID from template array here",
"templateRoles" => array(
array(
"tabs" => array(
"textTabs" => array (
array (
"tabLabel" => "lic_num",
"value" => "$license_number"
),
array (
"tabLabel" => "ubi_num",
"value" => "$ubi_number"
),
array (
"tabLabel" => "tra_nam",
"value" => "$trade_name"
)
)
),
"email" => "$applicant_email",
"name" => "$applicant_name",
"roleName" => "Applicant"
)
),
"status" => "sent"
);
Is this possible?
EDIT: So I got it to work using loops to get my data in the request, but I'm running into an interesting problem. If I put one or two templates in the envelope, it sends fine. If I put more than two in, it duplicates the templates. Here is my code for the complicated loops:
$compTempArray = array();
$applicant_name = $this->input->post("applicant_name");
$applicant_email = $this->input->post("applicant_email");
$license_number = $this->input->post("license_number");
$ubi_number = $this->input->post("ubi_number");
$trade_name = $this->input->post("trade_name");
foreach($hello as $key => $value) {
if(sizeof($hello) > 1) {
for($i = 1; $i < sizeof($hello); $i++) {
$compTempArray[] = array("serverTemplates" => array(
array(
"sequence" => $i,
"templateId" => $value
)
),
"inlineTemplates" => array(
array(
"sequence" => $i,
"recipients" => array(
"signers" => array(
array(
"tabs" => array(
"textTabs" => array (
array ("tabLabel" => "lic_num", "value" => $license_number),
array ("tabLabel" => "ubi_num", "value" => $ubi_number),
array ("tabLabel" => "tra_nam", "value" => $trade_name)
)
),
"email" => "*********#*****.com",
"name" => $applicant_name,
"recipientId" => "1",
"roleName" => "Applicant"
),
)
)
)
));
}
$data = array("accountId" => $accountId,
"emailSubject" => "Hello World!",
"emailBlurb" => "This comes from PHP",
"compositeTemplates" => $compTempArray,
"status" => "sent");
} else {
$data = array("accountId" => $accountId,
"emailSubject" => "Hello World!",
"emailBlurb" => "This comes from PHP",
"templateId" => "$value",
"templateRoles" => array(
array(
"tabs" => array(
"textTabs" => array (
array ("tabLabel" => "lic_num", "value" => $license_number),
array ("tabLabel" => "ubi_num", "value" => $ubi_number),
array ("tabLabel" => "tra_nam", "value" => $trade_name)
)
),
"email" => "*********#*****.com",
"name" => $applicant_name,
"roleName" => "Applicant"
)
),
"status" => "sent");
}
}
Any idea why it would do this?
NEW EDIT: Update on this weirdness: one to two - one copy of each template, three - it doubles the amount of each template, four - it triples the amount, five - it quadruples the amount.
NEWEST EDIT: So as it turns out, it was the for loop that I was using to try and increment the sequence. I got rid of the loop and hardcoded the sequence to 1. That fixed it.
To apply multiple templates to a single envelope you'll need to use the compositeTemplates structure.
compositeTemplates can get complex very quickly but they do allow for great flexibility and functionality for your envelopes. The API documentation is the best place to read about compositeTemplates but as previously mentioned the April 2012 Templates Webinar is also a good resource. The third example provides a basic use of compositeTemplates in that it shows you how to combine two server templates into one single envelope. You can use that as a base for your JSON.
To apply 2 server templates to a single envelope it uses the following JSON:
{
"emailSubject": "DocuSign Templates Webinar - Example 3",
"emailBlurb": "Example #3 - Composite Templates",
"status": "sent",
"compositeTemplates": [
{
"serverTemplates": [
{
"sequence": "1",
"templateId": "55A80182-2E9F-435D-9B16-FD1E1C0F9D74"
}
],
"inlineTemplates": [
{
"sequence": "1",
"recipients": {
"signers": [
{
"email": "firstrecipient#gmail.com",
"name": "John Doe",
"recipientId": "1",
"roleName": "RoleOne"
}
]
}
}
]
},
{
"serverTemplates": [
{
"sequence": "2",
"templateId": "44D9E888-3D86-4186-8EE9-7071BC87A0DA"
}
],
"inlineTemplates": [
{
"sequence": "2",
"recipients": {
"signers": [
{
"email": "secondrecipient#gmail.com",
"name": "Jane Doe",
"recipientId": "1",
"roleName": "RoleOne"
}
]
}
}
]
}
]
}
Note that the sequence value for each template determines the order of template application to the envelope. So in other words, the sequence value determines the document order, but since the templates might have matching/conflicting info (in terms of template roles for instance) the sequence value might also affect the end result of the envelope.

PHP return array of matching KEY NAMES and there values

I'm having a terrible time trying to pull out some values out of an array. Here is a slimmed down version of the array.
$properties = array( array( PropertyID => 2845,
Address_1 => "1234 Any street",
MEDIA_IMAGE_00 => "23428.jpg",
MEDIA_IMAGE_TEXT_00 => "Front of House",
MEDIA_IMAGE_01 => "29872.jpg",
MEDIA_IMAGE_TEXT_01 => "Master Bedroom",
MEDIA_IMAGE_02 => "29834.jpg"
),
array( PropertyID => 2845,
Address_1 => "555 This street",
MEDIA_IMAGE_00 => "234234.jpg",
MEDIA_IMAGE_TEXT_00 => "Front of House",
MEDIA_IMAGE_01 => "298724.jpg",
MEDIA_IMAGE_TEXT_01 => "Second Bedroom",
MEDIA_IMAGE_02 => "298346.jpg"
),
array( PropertyID => 2845,
Address_1 => "333 Main street",
MEDIA_IMAGE_00 => "2342845.jpg",
MEDIA_IMAGE_TEXT_00 => "Lounge",
MEDIA_IMAGE_01 => "2987246.jpg",
MEDIA_IMAGE_TEXT_01 => "Front of House",
MEDIA_IMAGE_02 => "2983434.jpg"
),
);
There is a massive amount of data in each sub array I've trimmed it down for length...
I'm inserting this data into a MySQL database, however, I'm inserting the images into a separate table [PropertyID, Image, ImageText] because some properties may have more images than others.
So now that the background is out of the way.
How do I pull just the keys of the array that match and there info into another array? So that I would end up with an array from the above that would end up with something similar to:
$property_images = array( array( PropertyID => 2845,
IMAGE => "23428.jpg",
IMAGE_TEXT => "Front of House"),
array( PropertyID => 2845,
IMAGE => "29872.jpg",
IMAGE_TEXT => "Master Bedroom",
array( PropertyID => 2845,
MEDIA_IMAGE_02 => "29834.jpg"
IMAGE_TEXT => "Living Room"
I've tried sscanf to no avail and fiddle around with array_keys but haven't managed to figure out how to target the key names rather than the key values...
Thanks for your help in advance!
Edit:
foreach( $properties as $v ) {
foreach( $v as $k => $m ) {
if( strpos($k, 'MEDIA_IMAGE_TEXT_') !== FALSE ) {
$new_array[] = array('PropertyID' => $v['PropertyID'], 'IMAGE'=>$prev, 'IMAGE_TEXT'=>$m );
}
if( strpos($k, 'MEDIA_IMAGE_') !== FALSE ) {
$prev = $m; //var_dump($prev);
}
}
}

Categories