0

I have an array which is something like this:

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

I want to sort this array based on the alphabetical order from the key "header" with PHP. I have tried usort and searched for built in functions but cannot find one (or looking past it). Is this possible with a single php function?

mauzilla
  • 3,304
  • 8
  • 46
  • 85

2 Answers2

0

have a look at "ksort"

it is very useful for arranging an array by its key.

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

that would display

a = minimum
c = mid
d = maximum

hopefully that's what you're after.

Source: PHP Manual

0

Look at this function from 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;
}
Chris
  • 3,891
  • 4
  • 37
  • 78