的大雁你的问题是,为了进行排序$oneline[4]
,这似乎包含一个字符串值,则需要以下步骤适用:
- 分割字符串到一个数组(
$oneline[4] = explode(',', $oneline[4])
)
- 排序所得到的阵列(
sort($oneline[4])
)
- 阵列组合成一个字符串(
$oneline[4] = implode(',', $oneline[4])
)
由于我得到的印象变量命名是低优先级列表中我重新使用$oneline[4]
变量。主要是为了澄清我所指代码的哪一部分。
话虽这么说,有你应该作出其他改善措施,如果你想成为未来的你自己说话了(如果你需要在一两个月的这个代码工作)
- 选择一个编码风格,并坚持下去,原来的代码看起来就像是复制/来自至少4个不同的来源(主要是不一致的报价的标志和大括号)
- 尽量限制重复昂贵的操作粘贴,例如只要你可以打开文件(公平地说,
agents.data
可以包含31行和d的users.txt
将被打开一次造成我看像一个傻瓜)
我已经更新了你的代码样本,试图说明我的意思通过上述几点。
<?php
error_reporting(0);
$lines = array();
$users = false;
$fp = fopen('http://20.19.202.221/exports/agents.data', 'r');
while ($fp && !feof($fp)) {
$line = trim(fgets($fp));
$lines[] = $line;
$oneline = explode('|', $line);
// if we have $users (starts as false, is turned into an array
// inside this if-block) or if we have collected 30 or more
// lines (this condition is only checked while $users = false)
if ($users || count($lines) > 30) {
// your code sample implies the users.txt to be small enough
// to process several times consider using some form of
// caching like this
if (!$users) {
// always initialize what you intend to use
$users = [];
$fz = fopen('users.txt', 'r');
while ($fz && !feof($fz)) {
$users[] = explode(',', trim(fgets($fz)));
}
// always close whatever you open.
fclose($fz);
}
// walk through $users, which contains the exploded contents
// of each line in users.txt
foreach ($users as $onematch) {
if (strpos($oneline[1], $onematch[1])) {
// now, the actual question: how to sort $oneline[4]
// as the requested example was not available at the
// time of writing, I assume
// it to be a string like: 'b,d,c,a'
// first, explode it into an array
$oneline[4] = explode(',', $oneline[4]);
// now sort it using the sort function of your liking
sort($oneline[4]);
// and implode the sorted array back into a string
$oneline[4] = implode(',', $oneline[4]);
echo $onematch[0], $oneline[4], '<br>';
}
}
}
}
fclose($fp);
我希望这不会冒犯你太多,只是试图帮助,而不仅仅是提供手头问题的解决方案。
你想如何对它们进行排序? – kittykittybangbang
也许你可以尝试保存从你的fopen()返回的数据并保存在一个json或数组上,然后你可以订购这个新的数组或json(本地存储) – BlackHack123
@kittykittybangbang我想按降序对它进行排序。 – JustinasT