【问题标题】:explode a:b to a:c php将 a:b 分解为 a:c php
【发布时间】:2016-03-30 19:42:40
【问题描述】:

例如,我有 2 个文件

file1.txt 和 文件2.txt

file1.txt 包含例如以下内容:

a:b
markus:lanz
peter:heinrichs
lach:schnell

并且file2.txt包含例如以下内容(file1.txt的第二次爆炸)

b:c
lanz:hallo
heinrichs:gruss
schnell:langsam

所以我想在 php 中有以下输出:

a:c
markus:hallo
peter:gruss
lach:langsam

这怎么可能?

先爆先搜还是怎样?

谢谢

我当前的代码如下:

<?php
$file1 = 'a:b
markus:lanz
peter:heinrichs
lach:schnell';

$file2 = '
lanz:hallo
heinrichs:gruss
b:c
test:notest
schnell:langsam';




  $array = explode(":", $file1);

  for($i=0; $i < count($array); $i++) {


  $array = explode(":", $file1);

 $pattan = $array[$i];
  $pattern = '=\n'. $pattan .':(.*)\n=sUm'; 
  $result = preg_match($pattern, $file2, $subpattern); 

 echo "<br>";
  echo $array[$i];
  $first = $array[$i];
  echo "<br>";
  }



  $pattern = '=\n'. $first .':(.*)\n=sUm'; 
  $result = preg_match($pattern, $file2, $subpattern); 
var_dump($subpattern); 

?>

我做错了什么?

【问题讨论】:

  • 你似乎在匹配位置,我不确定搜索的重点是什么
  • 如果数据是从实际文件中读取的,那么您应该首先使用file 来获取包含单行的数组。然后循环遍历它们,并在冒号处爆炸。
  • 希望例如 a:b 转到 a:c 不重要顺序如何
  • 显然错了。变量 $file1$file2 不包含您所描述的内容。例如,当您将$file1: 分解时,它会创建一个像这样的数组:{"a", "bmarkus", "lanzpeter", "heinrichslach", "schnell"},我认为这不是您期望的结果。
  • @MuntashirAkon 除非你用file()阅读文件。

标签: php explode


【解决方案1】:

您对此有何看法:

$file1="a:b
markus:lanz
peter:heinrichs
lach:schnell";

$file2="b:c
lanz:hallo
heinrichs:gruss
schnell:langsam";

$a1 = explode("\n",$file1);
$a2 = explode("\n",$file2);

if(count($a1) != count($a2)) die("files don't match!");

$final=array();
foreach($a1 as $k=>$line){
   $l1 = explode(":",$line);
   $l2 = explode(":",$a2[$k]);
   $final[]=$l1[0].':'.$l2[1];
}
print_r($final);

【讨论】:

    【解决方案2】:

    我会使用以下方法:

    // load your two files into arrays using file() and explode each line on ':'
    foreach ([1,2] as $n) {
       $files[$n] = array_map(function($x){ return explode(':', trim($x));}, file("file$n.txt"));
    }
    
    // with file1, fill the output array with 'a' values using 'b' as the key to output
    foreach ($files[1] as $ab) {
        $output[$ab[1]]['a'] = $ab[0];
    }
    
    // with file2, fill the output array with 'c' values, also using 'b' as the key
    foreach ($files[2] as $bc) {
        $output[$bc[0]]['c'] = $bc[1];
    }
    
    // remove any elements that do not have count 2 (i.e. both a and c values)
    $output = array_filter($output, function ($x) { return count($x) == 2; });
    

    【讨论】:

      猜你喜欢
      • 2018-09-25
      • 2021-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-16
      • 2011-11-26
      • 2014-03-16
      • 1970-01-01
      相关资源
      最近更新 更多