PHP Array (as xml seen) - php

I am trying to achieve this output from PHP array.
<Timesheets>
<Timesheet>
<EmployeeID>5e493b2e-c3ed-4172-95b2-593438101f76</EmployeeID>
<StartDate>2013-04-03</StartDate>
<EndDate>2013-04-10</EndDate>
<Status>Draft</Status>
<TimesheetLines>
<TimesheetLine>
<EarningsRateID>0daff504-2d42-4243-bdac-24f2bae0ce7c</EarningsRateID>
<NumberOfUnits>
<NumberOfUnit>8.00</NumberOfUnit>
<NumberOfUnit>8.00</NumberOfUnit>
<NumberOfUnit>8.00</NumberOfUnit>
<NumberOfUnit>8.00</NumberOfUnit>
<NumberOfUnit>8.00</NumberOfUnit>
<NumberOfUnit>0.00</NumberOfUnit>
<NumberOfUnit>0.00</NumberOfUnit>
</NumberOfUnits>
</TimesheetLine>
</TimesheetLines>
</Timesheet>
</Timesheets>
and my php code is (only array)
$new_timesheet = array();
$new_timesheet['Timesheet'] = array();
$new_timesheet['Timesheet']['EmployeeID'] = '8534e85a-e398-4041-99b1-cce51e7a8a02';
$new_timesheet['Timesheet']['StartDate'] = "2018-01-22";
$new_timesheet['Timesheet']['EndDate'] = "2018-01-28";
$new_timesheet['Timesheet']['Status'] = "Draft";
$new_timesheet['Timesheet']['Hours'] = "5.0";
$new_timesheet['Timesheet']['TimesheetLines'] = array();
$new_timesheet['Timesheet']['TimesheetLines']['TimesheetLine'] = array();
$new_timesheet['Timesheet']['TimesheetLines']['TimesheetLine']['EarningsRateID'] = '0daff504-2d42-4243-bdac-24f2bae0ce7c';
$new_timesheet['Timesheet']['TimesheetLines']['TimesheetLine']['NumberOfUnits'] = array();
$new_timesheet['Timesheet']['TimesheetLines']['TimesheetLine']['NumberOfUnits'][]['NumberOfUnit'] = array('8.00');
$new_timesheet['Timesheet']['TimesheetLines']['TimesheetLine']['NumberOfUnits'][]['NumberOfUnit'] = array('9.00');
but unexpectedly I am getting this output
<Timesheets>
<Timesheet>
<EmployeeID>8534e85a-e398-4041-99b1-cce51e7a8a02</EmployeeID>
<StartDate>2018-01-22</StartDate>
<EndDate>2018-01-28</EndDate>
<Status>Draft</Status>
<Hours>5.0</Hours>
<TimesheetLines>
<TimesheetLine>
<EarningsRateID>0daff504-2d42-4243-bdac-24f2bae0ce7c</EarningsRateID>
<NumberOfUnits>
<NumberOfUnit>8.00</NumberOfUnit>
</NumberOfUnits>
<NumberOfUnits>
<NumberOfUnit>9.00</NumberOfUnit>
</NumberOfUnits>
</TimesheetLine>
</TimesheetLines>
</Timesheet>
</Timesheets>
you can see it is repeating "NumberOfUnits" tag, which is incorrect.
Output should be as the first one.
can anybody do this for me?

As per your requirement, you have a NumberOfUnits array inside which there are multiple NumberOfUnit entries.
You can achieve the desired result by assigning to the NumberOfUnit array in the below manner
$new_timesheet['Timesheet']['TimesheetLines']['TimesheetLine']['NumberOfUnits']['NumberOfUnit'][] = '8.00';
$new_timesheet['Timesheet']['TimesheetLines']['TimesheetLine']['NumberOfUnits']['NumberOfUnit'][] = '9.00';

Related

Updating JSON file using PHP causes duplicate entries

I am trying to use PHP forms to update a JSON file, but when I edit a field of the file, it creates a duplicate of the entry, but with the updated information. For example:
[
{"toolName":"tool1", "url":"https://google.com/", "phase":"None"},
{"toolName":"tool2", "url":"http://yahoo.com/", "phase":"None"},
{"toolName":"tool3", "url":"http://bing.com/", "phase":"None"}
]
If on submission the PHP form wants to change the "phase" for "tool1", it adds a new entry with the updates. Like:
[
{"toolName":"tool1", "url":"https://google.com/", "phase":"None"},
{"toolName":"tool2", "url":"http://yahoo.com/", "phase":"None"},
{"toolName":"tool3", "url":"http://bing.com/", "phase":"None"},
{"toolName":"tool1", "url":"https://google.com/", "phase":"NewPhase"}
]
How can this be avoided? I am using the index of the tool in the array as the identifier when I update, so my current solution is this:
$toolId = $_POST['tool-id'];
$toolName = $_POST['tool-name'];
$toolUrl = $_POST['tool-url'];
$toolPhase = $_POST['tool-phase'];
$data = file_get_contents("../assets/js/tools.json");
$json_data = json_decode($data, true);
$json_data[$toolId]->toolName = $toolName;
$json_data[$toolId]->url = $toolUrl;
$json_data[$toolId]->phase = $toolPhase;
$json_data = array_values($json_data);
file_put_contents("../assets/js/tools.json", stripslashes(json_encode($json_data)));
**Note: When submitting the form, I am using a Bootstrap modal, so I am only sending the data for the current visible tool (i.e. the tool at index "toolId"), so I do not iterate through the entire JSON file.
The true statement in this line instructs PHP to return an array
$json_data = json_decode($data, true);
However, these lines create an object
$json_data[$toolId]->toolName = $toolName;
$json_data[$toolId]->url = $toolUrl;
$json_data[$toolId]->phase = $toolPhase;
If you change them to this it should work
$json_data[$toolId]['toolName'] = $toolName;
$json_data[$toolId]['url'] = $toolUrl;
$json_data[$toolId]['phase'] = $toolPhase;

Not receiveing output for Indexed Arrays

The output I am trying to receive is
"The Interest Rates are:
0.0525
0.0550
0.0575"
This will continue to $InterestRate7 value. I tried to link the new array elements with the old interest rate ($InterestRate1 = 0.0525; $RatesArray[1] = $InterestRate1) but it still does not work for me.Here is my code for extra help.
<?php
$InterestRate1 = 0.0525;
$InterestRate2 = 0.0550;
$InterestRate3 = 0.0575;
$InterestRate4 = 0.0600;
$InterestRate5 = 0.0625;
$InterestRate6 = 0.0650;
$InterestRate7 = 0.0700;
$RatesArray = array(
$RatesArray[1] = "0.0525";
$RatesArray[2] = "0.0550";
$RatesArray[3] = "0.0575";
$RatesArray[4] = "0.0600";
$RatesArray[5] = "0.0625";
$RatesArray[6] = "0.0650";
$RatesArray[7] = "0.0700";);
echo $RatesArray[1];
?>
The array() construct doesn't work quite like what you have here. Try something similar to the example in the php documentation http://php.net/manual/en/language.types.array.php
$RatesArray = array(
1 => "0.0525",
2 => "0.0550",
3 => "0.0575");

PHP Processing stream_get_contents into an array

I am having troubles converting a string which contains tab delimited CSV output
into an array. While using the following code :
$data = stream_get_contents($request->getShipmentReport());
I get back data as following:
Date Shipped Comments Feedback Arrived on Time
5/11/15 2 comment response Yes
Now I would like to process this data into an array with the returned headers(line 1) as the index containing the value for each line which follows after that.
I am trying to end up with something like this :
$line['Date'] = 5/11/15
$line['Shipped'] = 2
$line['Feedback'] = response
$line['Arrived on Time'] yes
What would be the best way to achieve this ?
I recommend using a library for handling CSV for example the CSV-Package by The League of Extraordinary Packages
You can pass your data and start working with array structures right away:
$csvString = stream_get_contents($request->getShipmentReport());
$csvReader = \League\Csv\Reader::createFromString($csvString);
$data = $csvReader->fetchAssoc(
array('Date', 'Shipped', 'Comments', 'Feedback', 'Arrived on Time')
);
// Or since line 0 contains header
$data = $csvReader->fetchAssoc(0); // 0 is offset of dataset containing keys
Now your data should be in a structure like:
$data = array(
array(
'Date' => '5/11/15',
'Shipped' => '2',
...
),
array(
...
)
);
You can even filter out specific datasets and all kinds of fancy stuff. Just check the documentation I linked to.
League CSV reader gives me a bad result. I use this instead:
$csvReportString = stream_get_contents($request->getReport());
$csvReportRows = explode("\n", $csvReportString);
$report = [];
foreach ($csvReportRows as $c) {
var_dump($c);
if ($c) { $report[] = str_getcsv($c, "\t");}
}
var_dump($report);

AddressDoctor WSDL and PHP

I am trying to CALL WSDL FROM php
http://validator2.addressdoctor.com/addBatch/Batch.asmx?wsdl
define('ADDRESSDOCTOR_WSDL_URL','http://validator2.addressdoctor.com/addBatch/Batch.asmx?wsdl');
define('ADDRESSDOCTOR_USER_LOGIN','myaccount');
define('ADDRESSDOCTOR_USER_PASSWORD','password');
$useinfo = array(
"CustomerID"=>ADDRESSDOCTOR_USER_LOGIN,
"DepartmentID"=>0,
"Password"=>ADDRESSDOCTOR_USER_PASSWORD
);
$addressinfo = array(
"Street"=>"main st",
"Locality"=>"wayne",
"PostalCode"=>"07035",
"Province"=>"NJ",
"Country"=>"USA");
$addressinfo1 = array(
"Street"=>"100 newark tpk",
"Locality"=>"wayne",
"PostalCode"=>"07470",
"Province"=>"NJ",
"Country"=>"USA");
$array_of_add = array("Address"=>$addressinfo,"Address"=>$addressinfo1);
$client = new SoapClient(ADDRESSDOCTOR_WSDL_UR);
$function = $client->Validate(array("addBatchRequest"=>array("Authentication"=>$useinfo,"Parameters"=>$paramenters,**"AddressCount"=>2**,"Addresses"=>$array_of_add)));
$result = $function->ValidateResult;
print_r($result);
It give me error
does not match number of supplied addresses.
If I write
$function = $client->Validate(array("addBatchRequest"=>array("Authentication"=>$useinfo,"Parameters"=>$paramenters,"AddressCount"=>1,"Addresses"=>$array_of_add)));
"AddressCount"=>2 is changed to "AddressCount"=>1
It works and outputs single result for "Address"=>$addressinfo1 even though i have passed two addresses Address"=>$addressinfo,"Address"=>$addressinfo1. I can pass upto 10 count in each batch request. But I am not able to get it. Can please some one help me what I am doing wrong.
I figured it out. I had to put
$array_of_add = array($addressinfo,$addressinfo1);
instead of
$array_of_add = array("Address"=>$addressinfo,"Address"=>$addressinfo1);

Decoding JSON into a PHP array, removing identical entries and encoding back to PHP

I'm having some trouble figuring out how to take JSON results from a MySQL query; turn them into a PHP array; remove the identical fields from that array, and turn the array back into JSON. The [1] is the part of the row with the actual JSON in it.
Am I missing something? Having trouble finding any similar questions on the site. Thanks!
$data = mysql_fetch_row($result);
print_r($data);
$json = json_decode($data[1], TRUE);
var_dump($json);
print_r($json);
$distinctresult = array_unique($json);
print_r($distinctresult);
$final = json_encode($distinctresult);
{"rows":[{"level":"ERROR","key":"Standard Not found","value":"RI.1.8"},{"level":"ERROR","key":"Standard Not found",{"level":"ERROR","key":"Standard Not found","value":"RI.K.9"},{"level":"ERROR","key":"Standard Not found","value":"RI.K.9"},{"level":"ERROR","key":"Standard Not found","value":"RI.K.9",}]}
Here's the MySQL query I'm using:
"select distinct d.valueField
from etllogs t
inner join etllogdetails d on t.uid = d.etllogID and d.valueField like '%ERROR%'
where t.transformationName like 'CM Data Extract'
and (t.timestamp >= (now() - interval 24 hour))
order by t.timestamp desc;";
It seems that you are trying to access array elements in a JSON encoded string ($data[1]).
I had success with the following code:
$data = array(0=>array('column1'=>'value1','column2'=>'value2'),
1=>array('column3'=>'value3','column4'=>'value3'));
$data_json=json_encode($data);
echo"ORIGINAL JSON:<pre>".print_r($data_json,true)."</pre>";
$data_php=json_decode($data_json,true);
echo"PHP ARRAY:<pre>".print_r($data_php,true)."</pre>";
$data_chunk=$data_php[1];
echo"PHP ARRAY CHUNK:<pre>".print_r($data_chunk,true)."</pre>";
$distinctresult = array_unique($data_chunk);
echo"UNIQUE CHUNK:<pre>".print_r($distinctresult,true)."</pre>";
$final = json_encode($distinctresult);
echo"FINAL JSON:<pre>".print_r($final,true)."</pre>";
http://phpfiddle.org/main/code/7dg-nnb

Categories