PHP拆分多个字符串
我有一个文本文件:“bookdata”,其结构如下:PHP拆分多个字符串,php,Php,我有一个文本文件:“bookdata”,其结构如下: abcd@yahoo.com:1:20.30 efgh@hotmail.com:4:5.05 ... 电子邮件:书籍总数:阅读的书籍总数 我的问题是使用关联数组将各个字符串的每个部分分开,如下所示: +-----------------------------------------------+ | yahoo.com | +---------------+-
abcd@yahoo.com:1:20.30
efgh@hotmail.com:4:5.05
...
电子邮件:书籍总数:阅读的书籍总数
我的问题是使用关联数组将各个字符串的每个部分分开,如下所示:
+-----------------------------------------------+
| yahoo.com |
+---------------+------------------+------------+
| abcd@yahoo.com | 1 | 20.30 |
| efgh@yahoo.com | 4 | 5.05 |
+---------------+------------------+------------+
我目前的做法如下:
我有一个函数makeArray(),其中包含读取txt文件中的数据:
public function makeArray()
{
$readTxtData = $this->read('bookdata');
//Get the domain from data....
$domain = preg_split("~[A-Za-z](.*?)@~", $readTxtData);
return $domain;
}
结果是:
Array
(
[0] =>
[1] => yahoo.com:7:8.35
[2] => hotmail.com:4:5.59
)
阵列应如下所示:
Array
(
[yahoo.com]
(
[0]
(
[0] => abcd@yahoo.com
[1] => 7
[2] => 8.35
)
[1] => Array
(
[0] => efgh@yahoo.com
[1] => 1
[2] => 8.36
)
[2] => Array
(
[0] => oyp@yahoo.com
[1] => 9
[2] => 13.42
)
).....
谢谢。假设您正在读取
$readTxtData
变量中的整个文本文件数据,问题的解决方案是这样的
public function makeArray(){
$readTxtData = $this->read('bookdata');
$lines = explode("\n", $readTxtData);
$result = array();
foreach($lines as $line){
$components = explode(":", $line);
$domain = explode("@", $components[0]);
$result[$domain[1]][] = $components;
}
return $result;
}
算法:
$result
的空数组
$result = array();
foreach
循环浏览文本文件的每一行,即$lines
,然后执行步骤3至5
foreach($lines as $line){
...
}
$line
,以获得所有三个组件,如电子邮件、书籍总数和在数组中读取的书籍总数,即$components
,如下所示:
Array
(
[0] => abcd@yahoo.com
[1] => 1
[2] => 20.30
)
Array
(
[0] => abcd
[1] => yahoo.com
)
此步骤由以下语句执行:
$components = explode(":", $line);
$domain = explode("@", $components[0]);
$components[0]
字符串以获取所有与域相关的组件,例如数组中的用户名和域名,即$domain
,如下所示:
Array
(
[0] => abcd@yahoo.com
[1] => 1
[2] => 20.30
)
Array
(
[0] => abcd
[1] => yahoo.com
)
此步骤由以下语句执行:
$components = explode(":", $line);
$domain = explode("@", $components[0]);
yahoo.com
作为$result
数组中的键,并相应地将$components
数组附加到它
$result[$domain[1]][] = $components;
$result
数组
return $result;