0
我有一個場景,我從兩個單獨的文件 - .xml
文件和.txt
文件中獲取數據 - 我嘗試使用PHP將2個數組(每個文件一個)組合在一個匹配值從每個。在數組上值合併
我沒有對上述文件的格式控制,因此使用下面的代碼到目前爲止,我已經把:
<?php
function dir_to_array($dir, $se) {
$result = array();
$cdir = scandir($dir);
foreach ($cdir as $key => $value) {
$file_info = pathinfo($value);
if (! in_array($value, array(".", ".."))) {
if (is_dir($dir . DIRECTORY_SEPARATOR . $value)) {
$result[$value] = dir_to_array($dir . DIRECTORY_SEPARATOR . $value);
} else {
if ($file_info['extension'] == 'xml') {
if (isset($se) && $se !== 'undefined') {
if (strpos($value, $se) !== false) {
$result['xml'] = xmlToArray(file_get_contents($dir.'/'.$value));
}
}
}
if ($file_info['extension'] == 'txt') {
$file = fopen($dir.'/'.$value, 'r');
$count = 0;
while (($line = fgetcsv($file)) !== FALSE) {
// trying to match the structure of the above array ($result['xml'])
$result['txt']['records']['PositionRecords']['record'][$count++] = $line;
}
fclose($file);
}
}
}
}
return json_encode($result);
}
echo dir_to_array('path/to/something', $arg);
我能夠得到以下陣列:
陣列1: .XML
[records] => Array
(
[PositionRecord] => Array
(
[record] => Array
(
[0] => Array
(
[keyword] => "something", // Value to match
[position] => "1"
),
...
)
)
)
陣列2: .TXT
[records] => Array
(
[PositionRecord] => Array
(
[record] => Array
(
[0] => Array
(
[0] => "something", // Value to match
[1] => "1000"
),
...
)
)
)
如何將加入關於匹配keyword
值這些陣列以最終獲得一個這樣的數組:
[records] => Array
(
[PositionRecord] => Array
(
[record] => Array
(
[0] => Array
(
[keyword] => "something",
[position] => "1",
[volume] => "1000"
),
...
)
)
)
我已經使用array_merge
試圖,array_merge_recursive
和array_combine
但是他們似乎只是將一個數組添加到另一個數組中。我也嘗試過this answer和this answer,它們都返回一個空數組[]
。