【问题标题】:How to explode an array of strings and store results in another array (php)如何分解字符串数组并将结果存储在另一个数组中(php)
【发布时间】:2017-10-18 13:30:53
【问题描述】:

有格式的文本文件:

(400, 530); 6.9; 5.7; 5.0;//------> continues for 100 values.

(500, 530); 7.9; 5.1; 5.0;

(600, 530); 6.7; 6.7; 7.2;

代码:

<?php
$file="./Speed10.asc";
$document=file_get_contents($file);
$rows = explode ('(', $document); //splits document into rows

foreach ($rows as &$rowvalue) {
     explode (';', $rowvalue);<----- How to assign each of these to member 
                                     of an array??
  }
}
?>

我正在尝试创建二维数组,首先拆分为行,然后按元素拆分为 ';'

【问题讨论】:

  • 你期望的输出是什么???
  • 这是$result[] = explode (';', $rowvalue);ok
  • 预期输出为 [1][0]: (400, 530); [1][1]:6.9; [1][2]:5.7; [1][3]:5.0;等
  • @KrisRoofe 谢谢你的回答,我说这会创建多个版本的 $result[] 是否正确?避免这种情况是我想不通的。

标签: php html arrays multidimensional-array data-extraction


【解决方案1】:

示例输入:

$document='(400, 530); 6.9; 5.7; 5.0; ...
(500, 530); 7.9; 5.1; 5.0; ...
(600, 530); 6.7; 6.7; 7.2; ...';

方法#1(不带分号的值存储在数组中):

foreach(explode("\r\n",$document) as $row){   // split the content by return then newline
    $result[]=explode("; ",$row);             // split each row by semi-colon then space
}
var_export($result);
/* Output:
    [
        ['(400, 530)','6.9','5.7','5.0','...'],
        ['(500, 530)','7.9','5.1','5.0','...'],
        ['(600, 530)','6.7','6.7','7.2','...']
    ]
) */

方法#2(带有分号的值存储在数组中):

foreach(explode("\r\n",$document) as $row){    // split the content by return then newline
    $result[]=preg_split('/(?<!,) /',$row);    // split each row by space not preceeded by comma
}
var_export($result);
/* Output:
    [
        ['(400, 530);','6.9;','5.7;','5.0;','...'],
        ['(500, 530);','7.9;','5.1;','5.0;','...'],
        ['(600, 530);','6.7;','6.7;','7.2;','...']
    ]
) */

这里是demo of both methods

请记住,我只关注循环内的字符串拆分。 Kris 对文件处理的建议是可取的。

根据您的环境,您可能需要通过删除 \r 或类似名称来调整第一次爆炸。

【讨论】:

  • @DanielRegan 如果这些结果都不是您想要的,请给我留言,详细解释哪里不太对。
  • 这正是我几天来一直在努力解决的问题。非常感谢。
猜你喜欢
  • 1970-01-01
  • 2011-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多