I have a multi-dim array from POST
[key:value key:value[array one {key1:value, key2:value}{key1:value, key2:value}][array two{key1:value, key2:value}...] key:value key:value]
I am producing xml entries with the nested arrays and identify them as follows:
foreach ($_POST as $key){
if (is_array($key)){
foreach ($key as $key2 => $value){
$array_type = substr($key2, 0,2);
if ($array_type == 'ec'){
$xml .= '<tns:PersonNamesInfoType>';
if ($key2 == 'ec_fname'){
$xml .= '<GivenName>'.$value.'</GivenName>';
//<MidInitial>MidInitial</MidInitial>
}
else if ($key2 == 'ec_lname'){
$xml .= '<FamilyName>'.$value.'</FamilyName>';
//</tns:PersonNamesInfoType>
}
else if ($key2 == 'ec_rel'){
$xml .= ' <Relationship>'.$value.' </Relationship>';
// <tns:PhoneInfoType>
//<tns:PhoneType></tns:PhoneType>
}
else if ($key2 == 'ec_ophone'){
$xml .= '<Number>'.$value.'</Number>';
}
else {
$xml .= '<IsPrimary>'.$value.'</IsPrimary>';
}
$xml .= '</tns:PersonNamesInfoType>';
}
else if($array_type == 've') {
$xml .= '<tns:AutoInfoType>';
foreach ($key as $key2 => $value){
if ($key2 == 'veh_year'){
$xml .= '<Year>'.$value.'</Year>';
}
else if ($key2 == 'veh_make'){
$xml .= '<Make>'.$value.'</Make>';
}
else if ($key2 == 'veh_model'){
$xml .= '<Model>'.$value.'</Model>';
}
else if ($key2 == 'veh_plate'){
$xml .= '<Plate>'.$value.'</Plate>';
}
else if ($key2 == 'veh_state'){
$xml .= '<tns:StateType>'.$value.'</tns:StateType>';
}
else {$xml .= '<IsPrimary>'.$value.'</IsPrimary>';}
}
$xml .= '</tns:AutoInfoType>';
}
}
}
}
This produces incorrect results
<tns:PersonNamesInfoType>
<GivenName>'.$value.'</GivenName>
</tns:PersonNamesInfoType>
<tns:PersonNamesInfoType>
<FamilyName>'.$value.'</FamilyName>
</tns:PersonNamesInfoType>
Instead of:
<tns:PersonNamesInfoType>
<GivenName>'.$value.'</GivenName>
<FamilyName>'.$value.'</FamilyName>
</tns:PersonNamesInfoType>
What is the better solution for segregating the data for each array based on the first key value coming across as
1[ec_fname]
1[veh_lname]
2[ec_fname]
2[veh_lname]
This will do what you need, and it’s shorter, simpler, and more easily expandable:
It looks like you had your loops set up wrong (there was a foreach loop in the vehicle section, but not one in the person section) and you were creating a new parent node every time a child node was created.
With my solution, instead of adding the nodes directly to the string on each loop iteration, they will instead be appended to an array, and then at the end of that
$_POSTvariable, the two arrays will be dumped into the correct parent node all at once.If you have to add another possible tag to either the person section or the vehicle section, all you need to do is add an entry to the
$personTagsor$vehicleTagsarray.