PHP如何?二維關聯陣列的排序

來源:互聯網
上載者:User
PHP怎麼實現二維關聯陣列的排序
比如數組是這樣的:


$example = array( array('b'=>7, 'rsd'=>6, 'gdd'=>3),
array('d'=>5, 'ess'=>8, 'ffs'=>5),
array('c'=>2, 'sdv'=>5, 'vfs'=>6),
array('a'=>8, 'hds'=>4, 'rfs'=>9));


不要用PHP系統函數,用uasort()或者uksort(),怎麼寫自訂的函數傳進去?
function compare($X, $Y)
這麼用uasort($example, 'compare'),
這個compare該怎麼寫?

不是關聯型的二維數組我知道怎麼寫compare,

function compare($x, $y)
{
if($x[0] == $y[0])
return 0;
elseif($x[0] < $y[0])
return -1;
else
return 1;
}

------解決方案--------------------
手冊 array_multisort
看例#4
------解決方案--------------------
Example #4 對資料庫結果進行排序


本例中 data數組中的每個單元表示一個表中的一行。這是典型的資料庫記錄的資料集合。


例子中的資料如下:


volume
------解決方案--------------------
edition
-------+--------
67
------解決方案--------------------
2
86
------解決方案--------------------
1
85
------解決方案--------------------
6
98
------解決方案--------------------
2
86
------解決方案--------------------
6
67
------解決方案--------------------
7


資料全都存放在名為 data的數組中。這通常是通過迴圈從資料庫取得的結果,例如 mysql_fetch_assoc()。


$data[] = array('volume' => 67, 'edition' => 2);
$data[] = array('volume' => 86, 'edition' => 1);
$data[] = array('volume' => 85, 'edition' => 6);
$data[] = array('volume' => 98, 'edition' => 2);
$data[] = array('volume' => 86, 'edition' => 6);
$data[] = array('volume' => 67, 'edition' => 7);
?>


本例中將把 volume 降序排列,把 edition 升序排列。


現在有了包含有行的數組,但是 array_multisort()需要一個包含列的數組,因此用以下代碼來取得列,然後排序。


// 取得列的列表
foreach ($data as $key => $row) {
$volume[$key] = $row['volume'];
$edition[$key] = $row['edition'];
}
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.