二維數組排序,且上標重新排

來源:互聯網
上載者:User
二維數組排序,且下標重新排
如題,我對某欄位排序,排好後,發現下標也跟著走,希望下標重新排,從0~開始排,問怎麼做?

------解決方案--------------------
PHP code
$fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");ksort($fruits);print "
";var_dump($fruits);
------解決方案--------------------
PHP code
$ar = array(       array("10", 11, 100, 100, "a"),       array(   1,  2, "2",   3,   1)      );   array_multisort($ar[0], SORT_ASC, SORT_STRING,                $ar[1], SORT_NUMERIC, SORT_DESC);//SORT_ASC, SORT_DESC, SORT_REGULAR,SORT_NUMERIC, SORT_STRINGprint "
";                print_r($ar);
------解決方案--------------------
我想你需要這個――
看清楚最後一段代碼的最後一個參數


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'];
}

// 將資料根據 volume 降序排列,根據 edition 升序排列
// 把 $data 作為最後一個參數,以通用鍵排序
array_multisort($volume, SORT_DESC, $edition, SORT_ASC, $data);
?>


資料集合現在排好序了,結果如下:


volume | edition
-------+--------
98 | 2
86 | 1
86 | 6
85 | 6
67 | 2
67 | 7



------解決方案--------------------
設 $t 是排序的結果,下標不是升序的
則 $t = array_values($t);
就可化為下標升序的了
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.