[英]PHP Array sorting within WHILE loop
我有一個大問題,我找不到任何對數組條目進行排序的方法。 我的代碼:
<?php
error_reporting(0);
$lines=array();
$fp=fopen('file.txt, 'r');
$i=0;
while (!feof($fp))
{
$line=fgets($fp);
$line=trim($line);
$lines[]=$line;
$oneline = explode("|", $line);
if($i>30){
$fz=fopen('users.txt', 'r');
while (!feof($fz))
{
$linez=fgets($fz);
$linez=trim($linez);
$lineza[]=$linez;
$onematch = explode(",", $linez);
if (strpos($oneline[1], $onematch[1])){
echo $onematch[0],$oneline[4],'<br>';
}
else{
}
rewind($onematch);
}
}
$i++;
}
fclose($fp);
?>
問題是,我想對$ oneline [4]回顯的項目進行排序。 我嘗試了stackoverflow的其他幾篇文章-但無法找到解決方案。
您的問題的答案是,為了對似乎包含字符串值的$oneline[4]
進行排序,您需要執行以下步驟:
$oneline[4] = explode(',', $oneline[4])
) sort($oneline[4])
( sort($oneline[4])
) $oneline[4] = implode(',', $oneline[4])
) 當我得到印象變量的命名在優先級列表中很低時,我正在重新使用$oneline[4]
變量。 通常是為了澄清我要指代的代碼部分。
話雖這么說,但如果您想和自己的未來說話(如果您需要在幾個月內使用此代碼),還應該做其他改進。
agents.data
可能包含31行,而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);
我希望這不會對您造成太大的傷害,只是嘗試提供幫助,而不僅僅是提供解決當前問題的方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.