我有一个场景,我从2个单独的文件中获取数据 - .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 - 包含520个元素
[records] => Array
(
[PositionRecord] => Array
(
[record] => Array
(
[0] => Array
(
[keyword] => "something", // Value to match
[position] => "1"
),
...
)
)
)
数组2: .txt - 包含260个元素
[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,它们都返回一个空数组[]
。
答案 0 :(得分:1)
尝试创建简单的数组,以便像
一样轻松遍历$result['txt']['records'][$count++] = ....
而不是
$result['txt']['records']['PositionRecords']['record'][$count++] = ....
现在你需要使用像
这样的逻辑$xmlArray=$result['xml']['records'][having xml data];//let
$txtArray=$result['txt']['records'][having text file data];//let
$resultArray=array();
// loop for xml data
foreach($xmlArray as $key => $value){
$keyword= $value['keyword'];// get the keyword from xml
// and search it in text file array
foreach($txtArray as $k=>$v){
if($keyword === $v[0]){ // if something matched
// then add to the result array
$resultArray[] = array(
'keyword'=>$keyword,
'volume'=>$v[1],
'position'=>$value['position']
);
}
}
}
希望这可能有助于解决您的问题。