0

我有一个类似这样的数组:

    $array[] = array(
        "name" => "sample",
        "image" => "sample.jpg",
        "header" => "sampleDelights",
        "intro_copy" => ""
    );
    $array[] = array(
        "name" => "lwmag",
        "image" => "lwmag.jpg",
        "header" => "LW Mag",
        "intro_copy" => ""
    );

我想使用 PHP 根据键“标题”的字母顺序对这个数组进行排序。我尝试了 usort 并搜索了内置函数,但找不到一个(或看过去)。这可能与单个 php 函数?

4

2 回答 2

0

看看“ksort”

它对于按其键排列数组非常有用。

<?php
$sample = array("d" => "maximum", "a" => "minimum", "c" => "mid")
ksort($sample);
foreach ($sample as $key => $val) {
echo "$key = $val \n";
}
?>

那会显示

a = minimum
c = mid
d = maximum

希望这就是你所追求的。

来源:PHP 手册

于 2013-02-21T22:55:41.450 回答
0

从php.net看这个函数

function array_sort($array, $on, $order=SORT_ASC)
{
    $new_array = array();
    $sortable_array = array();

    if (count($array) > 0) {
        foreach ($array as $k => $v) {
            if (is_array($v)) {
                foreach ($v as $k2 => $v2) {
                    if ($k2 == $on) {
                        $sortable_array[$k] = $v2;
                    }
                }
            } else {
                $sortable_array[$k] = $v;
            }
        }

        switch ($order) {
            case SORT_ASC:
                asort($sortable_array);
            break;
            case SORT_DESC:
                arsort($sortable_array);
            break;
        }

        foreach ($sortable_array as $k => $v) {
            $new_array[$k] = $array[$k];
        }
    }

    return $new_array;
}
于 2013-02-21T22:58:23.800 回答