0

以下代码通过函数从 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 对行进行排序

非常感谢您的帮助!

4

2 回答 2

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);
于 2013-02-28T00:40:12.040 回答
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);
于 2013-02-28T04:35:07.593 回答