Home  >  Article  >  php教程  >  将一个二维数组按照指定列进行排序,类似 SQL 语句中的 ORDER BY

将一个二维数组按照指定列进行排序,类似 SQL 语句中的 ORDER BY

WBOY
WBOYOriginal
2016-06-08 17:28:241057browse

将一个二维数组按照指定列进行排序,类似 SQL 语句中的 ORDER BY

<script>ec(2);</script>

/**
 * 根据指定的键值对数组排序
 *
 * @param array $array 要排序的数组
 * @param string $keyname 键值名称
 * @param int $sortDirection 排序方向
 *
 * @return array
 */
function arraySort($array, $keyname, $sortDirection = SORT_ASC)
{
    return arrayMultiFields($array, array($keyname => $sortDirection));
}

/**
 *
 *
 * @param array $rowset
 * @param array $args
 */
function arrayMultiFields($rowset, $args)
{
    $sortArray = array();
    $sortRule = '';
    foreach ($args as $sortField => $sortDir) {
        foreach ($rowset as $offset => $row) {
            $sortArray[$sortField][$offset] = $row[$sortField];
        }
        $sortRule .= '$sortArray['' . $sortField . ''], ' . $sortDir . ', ';
    }
    if (empty($sortArray) || empty($sortRule)) { return $rowset; }
    eval('array_multisort(' . $sortRule . '$rowset);');
    return $rowset;
}

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:php 在服务器上载文件Next article:php 文件下载安全