以下代码通过google函数获取结果。 这一切都很好我只想对结果进行排序。
如何对foreach循环字母ASC中的记录进行排序??
function fetch_google($terms="sample search",$numpages=1,$user_agent='Mozilla/5.0 (Windows NT 6.1; rv:8.0) Gecko/20100101 Firefox/8.0')
{
$searched="";
for($i=0;$i<=$numpages;$i++)
{
$ch = curl_init();
$url="http://www.google.com/search?hl=en&q=".urlencode($terms)."&start=".$i.'0';
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_USERAGENT, $user_agent);
curl_setopt ($ch, CURLOPT_HEADER, 0);
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_REFERER, 'http://www.google.com/');
curl_setopt ($ch,CURLOPT_CONNECTTIMEOUT,120);
curl_setopt ($ch,CURLOPT_TIMEOUT,120);
curl_setopt ($ch,CURLOPT_MAXREDIRS,10);
curl_setopt ($ch,CURLOPT_COOKIEFILE,"cookie.txt");
curl_setopt ($ch,CURLOPT_COOKIEJAR,"cookie.txt");
$searched=$searched.curl_exec ($ch);
curl_close ($ch);
}
$xml = new DOMDocument();
@$xml->loadHTML($searched);
foreach($xml->getElementsByTagName('a') as $lnk)
{
if($lnk->getAttribute('class')=='l')
{
$links[] = array(
'href' => $lnk->getAttribute('href'),
'title' => $lnk->nodeValue
);
}
}
return $links;
}
$content = fetch_google("exemple",1);
foreach($content as $elem)
{
echo "<a target=\"_blank\" href=$elem[href]>$elem[title]</a><br>";
}
我想按$ elem [title] ASC
对行进行排序帮助很多!
答案 0 :(得分:2)
想象一下这个使用函数usort()
$array = array (
array('href' => 'http://132', 'title' => 'yxz'),
array('href' => 'http://233', 'title' => 'abc'),
array('href' => 'http://324', 'title' => '123')
);
usort($array, function($a, $b) {
if($a['title'] === $b['title']) {
return 0;
}
return $a['title'] < $b['title'] ? - 1 : 1;
});
var_dump($array);
答案 1 :(得分:0)
试试这个:
$array = array (
array('href' => 'http://132', 'title' => 'yxz'),
array('href' => 'http://233', 'title' => 'abc'),
array('href' => 'http://324', 'title' => '123')
);
$sort = array();
foreach($array as $k=>$v) {
$sort['title'][$k] = $v['title'];
}
array_multisort($sort['title'], SORT_ASC, $array);
echo "<pre>";
print_r($array);