Loop Std object array from SOAP to Database PHP - php

Getting soap response as STD object.
I'm trying to put this into a mysql database.
for ($i = 0; $i < sizeof($getrelaties); $i++) {
$array = get_object_vars($getrelaties[$i]);
print "<pre>";
print_r($array);
print "</pre>";
print "<hr>";
foreach ($array as $key => $val) {
echo $key;
echo $val;
}
};
Im getting the keys (wich are the row names) and values. But kinda stuck on getting them to be seperated by , so I can put them in a query
this is one array out of the object.
(
[ID] => 4876260
[AddDatum] => 2015-09-24T09:16:00
[Code] => K0001
[Bedrijf] => Henk
[Contactpersoon] =>
[Geslacht] => m
[Adres] =>
[Postcode] =>
[Plaats] =>
[Land] =>
[Adres2] =>
[Postcode2] =>
[Plaats2] =>
[Land2] =>
[Telefoon] =>
[GSM] =>
[FAX] =>
[Email] => ******#gmail.com
[Site] =>
[Notitie] =>
[Bankrekening] =>
[Girorekening] =>
[BTWNummer] =>
[Aanhef] =>
[IBAN] =>
[BIC] =>
[BP] => B
[Def1] =>
[Def2] =>
[Def3] =>
[Def4] =>
[Def5] =>
[Def6] =>
[Def7] =>
[Def8] =>
[Def9] =>
[Def10] =>
[LA] => 0
[Gb_ID] => 0
[GeenEmail] => 0
[NieuwsbriefgroepenCount] => 0
)
The problem is that I want to put these arrays into the database .
I dont want to hardcode the rows.. Any suggestions?

Use serialize() to stringify the array and store in a BLOB or TEXT field in MySQL:
$serialized_array = serialize($array);
You can then SELECT this data back from the database as needed and make use of:
$data = unserialize($serialized_array);
This is 100% the way to go because the format of the arrays returned from the third-party SOAP service could change over time and you are not at the mercy of these changes and having to detect them and migrate your database schema accordingly etc.

Related

PHP search JSON without looping

I have a large JSON array which is the result of querying the API of an Icinga2 monitoring system.
I have used json_decode like this in my code to decode it:
$response = json_decode($array, true);
and I can see the output looks like this:
Array
(
[results] => Array
(
[0] => Array
(
[attrs] => Array
(
[__name] => HOSTNAME0
[acknowledgement] => 0
[acknowledgement_expiry] => 0
...
...
[state] => 0
[state_type] => 1
[meta] => Array
(
)
[name] => HOSTNAME0
[type] => Host
)
[1] => Array
(
[attrs] => Array
(
[__name] => HOSTNAME1
[acknowledgement] => 0
[acknowledgement_expiry] => 0
...
...
[state] => 0
[state_type] => 1
[meta] => Array
(
)
[name] => HOSTNAME1
[type] => Host
)
There are 400 Records in total and it's quite a complex structure but the only bits I am really interested in are the name and state fields.
Basically my script has a list of 150 hostnames from another source and what I want to do is for each hostname, search for it in the array and return the value of the state field for that host.
So far I've been struggling to do this without looping through the entire array for each of the 150 hostnames. There must be a more efficient way to do a lookup in the array based on a hostname and return a single value but I can't figure it out.
Given, the name field has no logical sorting inside the json result, there is no way to look at least once at each element. If they are sorted alphabetical, you could use a simple binary search, which would give you the result in O(log(n)).
The other thing is, if you have to search for multiple names, you could put them inside an name assiciated array. This way, you only have an initial overhead of O(n) building the list and each following search would return you the state on O(1).
// building the array
$states = [];
foreach ($items as $item) {
$states[$item['name']] = $item['state'];
}
looking for HOSTNAME1
$state = $states['HOSTNAME1'];
I'm hoping that I've got the source data array in the correct layout as the format was a bit confusing from the original question. But the main idea is to use array_column to extract the "attrs" and key the result by the "name" element of this array.
$response = Array(
"results" => Array(
0 => Array(
"attrs" => Array(
"__name" => "HOSTNAME0",
"acknowledgement" => 0,
"acknowledgement_expiry" => 0,
"state" => 0,
"state_type" => 1
),
"name" => "HOSTNAME0",
"type" => "Host"
),
1 => Array(
"attrs" => Array(
"__name" => "HOSTNAME1",
"acknowledgement" => 0,
"acknowledgement_expiry" => 0,
"state" => 2,
"state_type" => 1
),
"name" => "HOSTNAME1",
"type" => "Host1"
)
)
);
$extract = array_column($response["results"], "attrs", "name");
print_r($extract);
With the sample data, this gives...
Array
(
[HOSTNAME0] => Array
(
[__name] => HOSTNAME0
[acknowledgement] => 0
[acknowledgement_expiry] => 0
[state] => 0
[state_type] => 1
)
[HOSTNAME1] => Array
(
[__name] => HOSTNAME1
[acknowledgement] => 0
[acknowledgement_expiry] => 0
[state] => 2
[state_type] => 1
)
)
So to find any server by name, you'd use
echo "HOSTNAME1=".$extract["HOSTNAME1"]["state"].PHP_EOL;
If you only wanted the state field (as you asked for) and wanted to simplify the array, you can then use...
array_walk($extract, function(&$data) {$data=$data["state"];});
print_r($extract);
The array_walk() goes through the array and just copies the state field to be the entry, so the result of this is...
Array
(
[HOSTNAME0] => 0
[HOSTNAME1] => 2
)
So now you just do...
echo "HOSTNAME1=".$extract["HOSTNAME1"].PHP_EOL;

PHP get key value pairs out from an array within a new array (array filtering, array reducing)

I am having an associative array like this:
[1] => Array
(
[logo] =>
[starting] =>
[prelim_info] =>
[state_entry] => 1
[district_entry] => 3
[CLIx_code] => 1009
[survey_time] => 2017-05-29 09:38:00.0
[Implement_module] =>
[CLIxModule_Impl] => 1
[Noimplement_reason] =>
[Other_Reason] =>
[implementedModule_Name] => 7 10 11 12
[Lab_Open] => 3
[Lab_Management] => 1
[Planned_CLIxPeriods] => 2
[ReasonsCancellation_CLIxClass] => 5
[PowerCut_Visit] => 2
[Observe_session:Session_observe] => 2
[Observe_session:grade_observe] =>
[Observe_session:grade_other] =>
[Observe_session:Module_Observed] =>
[Observe_session:Unit_Observed] =>
[Observe_session:Lesson_Observed] =>
[Observe_session:time_Sufficient] =>
[Observe_session:Student_workindependent] =>
[Observe_session:groupsinteracting] =>
[Observe_session:groupshelping] =>
[Observe_session:Students_Mothertongue] =>
[Observe_session:Students_handbook] =>
[Observe_session:Students_reflections] =>
[Observe_session:teacherpresent] =>
[Observe_session:encourage_platform] =>
[Observe_session:encourage_classdisc] =>
[Observe_session:mothertongue_teacher] =>
[Observe_session:teacher_handbook] =>
[Observe_session:Teacher_prepared] =>
[TPDcertification_support1:TPD_Cert_Subject1] =>
[TPDcertification_support1:tchrSupport_TPD1] =>
[TPDcertification_support1:Source_Support] =>
[TPDcertification_support2:TPD_Cert_Subject2] =>
[TPDcertification_support2:tchrSupport_TPD2] =>
[TPDcertification_support2:Source_Support] =>
[TPDcertification_support3:TPD_Cert_Subject] =>
[TPDcertification_support3:tchrSupport_TPD3] =>
[TPDcertification_support3:Source_Support] =>
[TPDcertification_support4:TPD_Cert_Subject] =>
[TPDcertification_support4:tchrSupport_TPD4] =>
[TPDcertification_support4:Source_Support] =>
[teacher_feedback] => Regarding the old modules, maths teachers said that it was very useful as well as workbook.
[FSP_feedback] => NA
[TPDsuppport_certification:Supt_TPDcertification] => 1
[TPDsuppport_certification:Source_Supportcertification] => 4
[teacherSupport_moduleImplement] => They had training organised by the clix team and RMSA.
[HighPoint] => NA
[LowPoint] => There was no clix class since school reopen.
[schlcontact_FSP_nooftimes] => 0
[FT_contactreason] => 5
[FT_otherreason] =>
[Support_fromTE] => 2
[Action_FT] => 1
[Specific_ActionFT] => School lab need to recheck for start rolling out the modules.
[Action_CLIxTeam] => 2
[Sepecific_ActionCLIx] =>
[Action_State] => 1
[Specific_ActionState] => To issue the class period include in their regular time table.
[Action_TPD] => 2
[Specific_ActionTPD] =>
[Session_observe2:Module_Second] =>
[Session_observe2:Observe_grade] =>
[Session_observe2:other_grade] =>
[Session_observe2:Observation_Module2] =>
[Session_observe2:Observation_Unit2] =>
[Session_observe2:Observation_Lesson2] =>
[Session_observe2:time_Sufficient2] =>
[Session_observe2:Student_workindependent2] =>
[Session_observe2:groupsinteracting2] =>
[Session_observe2:groupshelping2] =>
[Session_observe2:Students_Mothertongue2] =>
[Session_observe2:Students_handbook2] =>
[Session_observe2:Students_reflections2] =>
[Session_observe2:teacherpresent2] =>
[Session_observe2:encourage_platform2] =>
[Session_observe2:encourage_classdisc2] =>
[Session_observe2:mothertongue_teacher2] =>
[Session_observe2:teacher_handbook2] =>
[Session_observe2:Teacher_prepared2] =>
[teacher_feedback2] =>
[FSP_feedback2] =>
[TPD_certification:tcher_TPD] =>
[TPD_certification:certification_course_tchr_suport] =>
[teachersupport_moduleImplement2] =>
[school_location:Latitude] => 23.7428370300
[school_location:Longitude] => 92.7227306900
[school_location:Altitude] => 1014.0000000000
[school_location:Accuracy] => 18.0000000000
[generated_note_name_110] =>
[meta:instanceID] => uuid:2568400e-0ec3-421d-94bc-10653732e6d2
)
I want some key-value pairs from this array for data analysis and visualization. the output should look something like this:-
array(
[CLIx_code] => 1009
[state_entry] => 1
[district_entry] => 3
...
)
Basically, I want an array with a few key value pairs filtered on which I can operate some mathematical functions and pass those to D3.js for data visualization.
I tried it this way:
for ($i=0;$i<count($all_rows);$i++){
$filteredarray[] = array($all_rows[$i]['CLIx_code'], $all_rows[$i]['state_entry'], $all_rows[$i]['district_entry']);
}`
But I want key value pairs not only the value I even tried using array_filter().
I have to assume you know the key names for the elements that you want to retain and run calculations on, so array_intersect_key() is the right tool for the job.
Code (Demo):
$array=[
'logo'=>'',
'starting'=>'',
'prelim_info'=>'',
'state_entry'=>1,
'district_entry'=>3,
'CLIx_code'=>1009
// ... more elements
];
$filterkeys=[
'state_entry',
'district_entry',
'CLIx_code'
// ... more key names
];
var_export(array_intersect_key($array,array_flip($filterkeys)));
Output:
array (
'state_entry' => 1,
'district_entry' => 3,
'CLIx_code' => 1009,
)
Alternatively, you can drop the array_flip() call if you set your $filterkeys key names as keys, like this:
$filterkeys=[
'state_entry'=>'',
'district_entry'=>'',
'CLIx_code'=>''
// ... more key names
];
var_export(array_intersect_key($array,$filterkeys));
PHP: How to use array_filter() to filter array keys?
Just refer this Question's answer
Like in your case you need to write some code like below:-
<?php
//You have below array including all keys
$result_array = array('logo'=>'test','state_id'=>125,'prelim_info'=>'','CLIxModule_Impl'=>'5','district_entry'=>3);
// Now provide only those keys which you need to filter.
$filter_keys = array('district_entry','state_id');
$filtered_array = array_filter($result_array,
function ($key) use ($filter_keys) {
return in_array($key, $filter_keys);
},
ARRAY_FILTER_USE_KEY
);
var_dump($filtered_array);
?>

Building Dynamic array with PHP

I'm pulling results from an XML SOAP service which returns results in structure that doesn't work too well with encoding the result to json then decoding into an array.
Here's an example of the output I've rendered by running the following function on my results:
$result[implode('/',$keys)] = $val;
Array
(
[accountList/accountNo] => 0610010000048744
[accountList/accountOpeningDate] => 2014-09-01T00:00:00+03:00
[accountList/accountStatus] => DORMANT
[accountList/arrearAmount] => 80000.0
[accountList/arrearDays] => 30
[accountList/balanceAmount] => 120000.0
[accountList/disputed] => false
[accountList/isMyAccount] => false
[accountList/lastPaymentDate] => 2015-01-23T00:00:00+03:00
[accountList/listingDate] => 2014-09-30T00:00:00+03:00
[accountList/pastDueDate] => 1900-01-01T00:00:00+03:00
[accountList/principalAmount] => 300000.0
[accountList/scheduledPaymentAmount] => 0.0
[accountList/tradeSector] => Bank Sector Bureau
[accountList/worstArrear] => 30
[accountList/currency] => KES
[personalProfile/crn] => 79908
[personalProfile/dateOfBirth] => 1959-01-01T00:00:00+02:45
[personalProfile/fullName] => Surname 79908 OtherNames 79908
[personalProfile/gender] => F
[personalProfile/nationalID] => ID79908
[summary/npaAccounts/mySector] => 2
[summary/npaAccounts/otherSectors] => 0
[summary/npaTotalValueList/currency] => KES
[summary/npaTotalValueList/mySector] => 120000.0
[summary/npaTotalValueList/otherSectors] => 0.0
[summary/openAccounts/mySector] => 2
[summary/openAccounts/otherSectors] => 0
)
Because the results and keys always vary depending on request I make to the server, I'd like to build a multidimensional array through a recursive function, in some instances the keys eg. accountList may have multiple values
An expected result would look something like this:
Array
(
[accountList] => Array
(
[accountNo] => 0610010000048744
[accountOpeningDate] => 2014-09-01T00:00:00+03:00
[accountStatus] => DORMANT
[arrearAmount] => 80000.0
[arrearDays] => 30
[balanceAmount] => 120000.0
[disputed] => false
[isMyAccount] => false
[lastPaymentDate] => 2015-01-23T00:00:00+03:00
[listingDate] => 2014-09-30T00:00:00+03:00
[pastDueDate] => 1900-01-01T00:00:00+03:00
[principalAmount] => 300000.0
[scheduledPaymentAmount] => 0.0
[tradeSector] => Bank, Sector Bureau
[worstArrear] => 30
[currency] => KES
)
Array
(
[accountNo] => 0610010000048788
[accountOpeningDate] => 2014-09-01T00:00:00+03:00
[accountStatus] => ACTIVE
[arrearAmount] => 10000.0
[arrearDays] => 90
[balanceAmount] => 10000.0
[disputed] => TRUE
[isMyAccount] => false
[lastPaymentDate] => 2015-01-23T00:00:00+03:00
[listingDate] => 2014-09-30T00:00:00+03:00
[pastDueDate] => 1900-01-01T00:00:00+03:00
[principalAmount] => 300000.0
[scheduledPaymentAmount] => 0.0
[tradeSector] => Bank, Sector Bureau
[worstArrear] => 30
[currency] => KES
)
[personalProfile] => Array
(
[crn] => 79908
[dateOfBirth] => 1959-01-01T00:00:00+02:45
[fullName] => Surname, 79908 OtherNames 79908
[gender] => F
[nationalID] => ID79908
)
)
I think you are trying to achieve this thing.
Try this code snippet here
explode("/", $key) this will return array which will contain two values.
list($first,$second)=explode("/", $key); and through this i am putting those values, one in $first and other in $second.
<?php
ini_set('display_errors', 1);
$data=Array
(
"accountList/accountNo"=>"0610010000048744",
"accountList/accountOpeningDate"=>"2014-09-01T00:00:00+03:00",
"accountList/accountStatus"=>"DORMANT",
"accountList/arrearAmount"=>"80000.0",
"accountList/arrearDays"=>"30",
"accountList/balanceAmount"=>"120000.0",
"accountList/disputed"=>"false",
"accountList/isMyAccount"=>"false",
"accountList/lastPaymentDate"=>"2015-01-23T00:00:00+03:00",
"accountList/listingDate"=>"2014-09-30T00:00:00+03:00",
"accountList/pastDueDate"=>"1900-01-01T00:00:00+03:00",
"accountList/principalAmount"=>"300000.0",
"accountList/scheduledPaymentAmount"=>"0.0",
"accountList/tradeSector"=>"Bank, Sector Bureau",
"accountList/worstArrear"=>"30",
"accountList/currency"=>"KES",
"personalProfile/crn"=>"79908",
"personalProfile/dateOfBirth"=>"1959-01-01T00:00:00+02:45",
"personalProfile/fullName"=>"Surname, 79908 OtherNames 79908",
"personalProfile/gender"=>"F",
"personalProfile/nationalID"=>"ID79908",
"sample/data/data1"=>"ID79908",//added a sample data
);
$result=array();
foreach($data as $key => $value)
{
$string="";
$numberOfWords=explode("/", $key);
foreach($numberOfWords as $newValue)
{
$string.="['$newValue']";
}
eval('$result'.$string."= \"$value\";");
}
print_r($result);
The way you want to build your array is as follows. The reason is that you want things like "accountList" and "personalProfile" to be unique keys within the array, much like they would be in a relational database.
$array = $array('accountList'=>array("accountNo"=>"0610010000048744",
"accountOpenDate"=>"2014-09-
01T00:00:00+03:00"),array("personalProfile"=>array("...and so on."));

Array index stuck at [0]

I am trying to create an array out of looped data. The variables contain looped data. All works fine, but when array is outputted, the index gets stuck at 0 and doesn't move up from 0 to 1 etc. I wonder what the problem is and how I can get this fixed.
Thanks.
$productinfo = array(
array(
"Productname" => "$productname",
"StarRating" => "$starrating",
"AddedValue" => "$addedvalue",
"ProductImage" => "$image",
"TotalPrice" => "$totalprice",
"ProductLink" => "$link" )
);
$productinfojson= json_encode($productinfo);
$output = json_decode($productinfojson, TRUE);
echo "<pre>";
print_r( $output );
echo "</pre>";
The above outputs:
Array
(
[0] => Array
(
[Procuctname] => Pencil Stack
[StarRating] => 3
[AddedValue] => Free Delivery
[ProductImage] =>
[TotalPrice] => 5.50
[ProductLink] => http://---.net/product
)
)
Array
(
[0] => Array
(
[Procuctname] => Block Bundle
[StarRating] => 4
[AddedValue] => Free Delivery
[ProductImage] =>
[TotalPrice] => 15
[ProductLink] => http://---.net/product
)
)
UPDATE if only one array is used.
code:
$productinfo = array(
"Productname" => "$productname",
"StarRating" => "$starrating",
"AddedValue" => "$addedvalue",
"ProductImage" => "$image",
"TotalPrice" => "$totalprice",
"ProductLink" => "$link" );
OUTPUT
Array
(
[Procuctname] => Pencil Stack
[StarRating] => 3
[AddedValue] => Free Delivery
[ProductImage] =>
[TotalPrice] => 5.50
[ProductLink] => http://---.net/product
)
Array
(
[Procuctname] => Block Bundle
[StarRating] => 4
[AddedValue] => Free Delivery
[ProductImage] =>
[TotalPrice] => 15
[ProductLink] => http://---.net/product
)
The issue stems straight from your array creation. There doesn't seem to be a loop anywhere in your code either....
Anyways, lets sort out your array creation. I assume you're getting the data from a database/data source and assigning it to variables, inputting it into an array? Well the way you currently have it, it's overwriting the first index element in the array.
Disclaimer: The below is pseudo code, until you update with your actual loop code..
$productinfo = array();
while($row = FETCH_DATA_FROM_SQL()) {
// assign it to variables here...?
$productinfo[] = array(
"Productname" => "$productname",
"StarRating" => "$starrating",
"AddedValue" => "$addedvalue",
"ProductImage" => "$image",
"TotalPrice" => "$totalprice",
"ProductLink" => "$link"
);
}
That will add each element to the new $productinfo array and you should be able to loop through the elements correctly.
One more thing to note, you're decoding your json like this:
$output = json_decode($productinfojson, TRUE);
That second parameter (TRUE), turns it into an associative array, not an object. So when you loop it as an object like below:
foreach($response->products->product as $product) {...
It isn't going to work. If you want it as an object, remove the second parameter (TRUE), otherwise loop it as an array:
foreach($response['products']['product'] as $product) {...

Problem With SimpleXML Parsing WoWArmory attributes

This is an example item:
SimpleXMLElement Object
(
[#attributes] => Array
(
[displayInfoId] => 62116
[durability] => 100
[gem0Id] => 41401
[gem1Id] => 40123
[gem2Id] => 0
[gemIcon0] => inv_jewelcrafting_shadowspirit_02
[gemIcon1] => inv_jewelcrafting_gem_37
[icon] => inv_helmet_98
[id] => 48592
[level] => 245
[maxDurability] => 100
[name] => Liadrin's Headpiece of Triumph
[permanentEnchantIcon] => ability_warrior_shieldmastery
[permanentEnchantItemId] => 44876
[permanentenchant] => 3819
[pickUp] => PickUpLargeChain
[putDown] => PutDownLArgeChain
[randomPropertiesId] => 0
[rarity] => 4
[seed] => 0
[slot] => 0
)
)
I'm trying to get a JSON object with each item, but there's about 17 or something, and if I try to json_encode() it's giving me "#attributes" as an object containing all the stuff I want. Help?
Something like this:
<?php
$sxm = new SimpleXMLElement("<a name=\"kkk\" other=\"foo\"/>");
$attrs = $sxm->attributes();
var_dump(json_encode(reset($attrs)));
gives:
string(28) "{"name":"kkk","other":"foo"}"
The problem you were experiencing was because $xmlObj->attributes() returns a SimpleXMLElement that, when converted as an array, is an array with the key "#attributes" and a value with an array that actually has the attributes as (name => value) pairs.
How about this
$jsonArray = array();
foreach ($xmlObj->attributes() as $attr => $value) {
$jsonArray[$attr] = (string)$value;
}
$jsonString = json_encode($jsonArray);
Edit: You may also be able to simply use
$jsonString = json_encode($xmlObj->attributes());
however I'm not sure if the attribute values are returned as strings or objects (edit - turns out you can't. See Artefacto's solution).
How about this?
$array = (array)$simplexml->node->attributes();
$jsonArray = json_encode($array['#attributes']);

Categories