【发布时间】:2021-12-16 02:11:58
【问题描述】:
你好 :) 我被困在我的迷你应用程序开发中。我有以下文字,从第 3 方网页复制:
Type A GZ 600 11.09.2021 12:00 OST 9
Type A GZ 601 11.09.2021 13:20 ADS 1
Type A GZ 602 11.09.2021 21:35 OCS 1
Type A GZ 603 11.09.2021 14:50 CSE 10
Type B GZ 600 11.09.2021 12:00 OST 5
Type B GZ 601 11.09.2021 13:20 ADS 3
Type B GZ 602 11.09.2021 21:35 OCS 6
Type B GZ 603 11.09.2021 14:50 CSE 12
我需要将其解析为以下格式:
$s = 10, $ns = 11, $bs = 26,点赞:
echo "S:" . $s . " NS:" . $ns . " BS:" . $bs; // Output: S:10 NS:11 BS:26
where:
$fa = array("OCS", "CSE"); is array of codes
$ns is sum of Type A last column numbers, which 5 column 3-letter code is in the array,
$s is sum of Type A last column numbers, which 5 column 3-letter code is not in the array
$bs is just sum of Type B last column numbers
我现在的代码如下:
if(!empty($_POST['indata'])){
$in_data = $_POST['indata']; // Get POST data
$fa = array("OCS", "CSE"); // Make array
$ns = 0; // Init ns value
$s = 0; // Init ss value
foreach(explode("/n",$in_data) as $line){ // Divide text to lines
$info[] = explode(" ", $line); // Divide line to values and put them to array
print_r($info); //Show input for test purposes
if(in_array($info[4], $fa)) { // Check, if 4th array value (code) is in array
$ns = $ns + $info[5]; // plus to $ns, if yes
} else {
$s = $s + $info[5]; // plus to $s, if no
}
unset($info); // clear array for next usage
}
}
但它似乎没有将线切割成数组。它只是向我显示线条,而不是划分为数组。我使用的是 Summernote 文本编辑器,它以行的形式发送数据。
【问题讨论】:
-
你的代码需要大量的cmets来解释,我还是一个都看不懂。
-
我认为错误在
"/n"。我想你打算使用"\n",一个反斜杠而不是一个正斜杠? -
也许有标签标志?尝试用
"\t"炸开$line。 -
不,不是制表符,而是 4 个空格。已检查。
-
@Serique 好吧.. 确实如此。的种类 ;)。不过,您需要考虑 $info 在您的代码中的外观。正如其他人已经说过的那样,
$info[]=...导致它的深度为 2 级,而不是您的代码所期望的 1 级。如果您将其更改为$info = ...,它应该会更好。此外,您实际上并不需要 unset(),除非您稍后在代码中使用 $info。
标签: php arrays parsing textarea