0

I am loading data from an XML file and also trying to dynamically be able to match these values from the XML elements, in to my database table. I am using Laravel 5.6.

This is what I have now:

config.php:

'milestone' => [
     'columns'  => array(       
         "JobDept"                      => "department",
         "JobBranch"                    => "branch",
         "Destination"                  => "destination",
      ),
 ],

The above array have the following format, which maps my XML fle to my database columns:

"XML Element Name => Database Column Name"

So, I can now take the keys from above array (JobDept, JobBranch, Destination) and find these in my XML files:

$data = $xml->parse([
    'report' => ['uses' => 'item['.implode(",",$xmlFilters).']', 'default' => null]
]);

Above works just fine. This will populate the keys with actual values from my XML file:

0 => array:3 [▼
  "JobDept" => "FEA"
  "JobBranch" => "AAL"
  "Destination" => "TWTPE"
]

This is where I am stuck. Since my column names in my MySQL database is department, branch, destination I guess I need to change the array key names, to match my database column names, so the array will be like this:

0 => array:3 [▼
  "department" => "FEA"
  "branch" => "AAL"
  "destination" => "TWTPE"
]

Any idea on how to achieve this dynamically? As said, I am using Laravel 5.6 as a framework.

Update: This is my $data array:

"report" => array:1[▼
        0 => array:3 [▼
          "JobDept" => "FEA"
          "JobBranch" => "AAL"
          "Destination" => "TWTPE"
        ]
 ]
1
  • Replace key with milestone[columns][key] Commented Jul 19, 2018 at 7:32

1 Answer 1

2

A simple example (fiddle):

$array = [
    "JobDept" => "FEA",
    "JobBranch" => "AAL",
    "Destination" => "TWTPE",
];
$replace = [
    "JobDept"                      => "department",
    "JobBranch"                    => "branch",
    "Destination"                  => "destination",
];

$new_array = [];
foreach ($array as $k => $v) {
    $new_array[$replace[$k]] = $v;
}
print_r($new_array);
Sign up to request clarification or add additional context in comments.

5 Comments

I have also created a fiddle here to demonstrate: fiddle
And what? Iterate over array[report] if you need to replace keys in report subarray.
Still does not work. As soon as my $array gets more items, I get the Undefined offset error. See my updated Fiddle
Now report is array of arrays and you need two foreach loops. If you don;t know how to iterate over nested arrays that's another question, not what you ask originally.
Ah. Would you mind updating your answer to reflect the two foreach loop? Would be much appreciated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.