【问题标题】:PHP: Getting values from array indexPHP:从数组索引中获取值
【发布时间】:2016-02-03 21:56:12
【问题描述】:

我有数据文件。每一行都有作者/作者的名字。它看起来像这样:

"Giacometti, Jasminka"; "Mazor Jolic, Slavica"; "Josic, Djuro";
"Hoffmeister, Karin M"; "Grozovsky, Renata"; "Jurak Begonja, Antonija"; "Hartwig, John H";
"Jakopovic, Boris"; "Kraljevic Pavelic, Sandra"; "BelScak-Cvitanovic, Ana"; "Harej, Anja"; "Jakopovich, Ivan";

例如,对于第一行:

"Giacometti, Jasminka"; "Mazor Jolic, Slavica"; "Josic, Djuro";

我需要得到这个并将其写入另一个文件:

"Giacometti, Jasminka"; "Mazor Jolic, Slavica";1
"Giacometti, Jasminka"; "Josic, Djuro";1
"Mazor Jolic, Slavica"; "Josic, Djuro";1

我如何在 php 中做到这一点?我尝试获取数组中的每一行,但后来我不知道如何从该行拆分数据。

$handle = @fopen("datas.txt", "r");
$listA = array();
if ($handle) {
    while (($buffer = fgets($handle, 4096)) !== false) {
        $listA[] = $buffer; 
}

谢谢。

【问题讨论】:

    标签: php arrays file


    【解决方案1】:

    首先从包含数据的文件中读取内容内容作为完整的一个完整字符串,然后用行尾字符分解该字符串,因此每个数组元素现在将包含一行数据:

    $data = file_get_contents("data.txt"); //data.txt is the file that contains rows of data
    
    $authArr = explode(PHP_EOL, $data ); //this array contains all the rows in it
    

    您现在可以使用此$authArr 写入另一个文件,方法是在每一行(即您将写入文件的数组的每个元素)附加一个换行符。

    【讨论】:

    • 是的,但我仍然不明白如何拆分数据,例如$authArr[5]。
    • 使用foreach()循环遍历$authArr数组
    • 谢谢,我做的有点不同,但这很有帮助。 $newElement= explode(";", $authArr[5]);
    【解决方案2】:
    foreach ( $$listA as $key)
        {
        $part = explode(";",$key); 
        }
    

    使用; 作为分隔符来拆分字符串。您必须丢弃 $part 数组的最后一个元素,因为它将是 ''。

    这里数组中只有三个元素。所以你不需要循环进行置换。如果您有更多号码,请使用permutations by loop。

    【讨论】:

      【解决方案3】:

      我不确定你想对作者做什么,但这会将每一行分成一组作者;

      <?php
      
      $source_string = file_get_contents('source.txt');   // Load the source file.
      $source_array = explode(PHP_EOL, $source_string);   // Create an array of one element per line.
      
      // Iterate over the source array.
      foreach($source_array as $line) {
        $trimmed = rtrim($line, ';');                     // Trim the semicolon from the end of the line.
        $array_of_authors = explode('; ', $trimmed);      // Explode the line into an array of one element per author.
        $output = print_r($array_of_authors, true);
        echo "<div>Line: {$line}</div>";
        echo "<xmp>{$output}</xmp>";
      }
      
      ?>
      

      上面产生的输出是这样开始的;

      Line: "Giacometti, Jasminka"; "Mazor Jolic, Slavica"; "Josic, Djuro";
      
      Array
      (
          [0] => "Giacometti, Jasminka"
          [1] => "Mazor Jolic, Slavica"
          [2] => "Josic, Djuro"
      )
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-03-20
        • 2017-11-08
        • 1970-01-01
        • 1970-01-01
        • 2011-02-26
        • 1970-01-01
        • 2011-04-15
        相关资源
        最近更新 更多