1

Sort multi dimensional array

$list = array_sort($list, 'name', SORT_ASC);
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;
}
//Prepare Array List
$list = array(
    array('type' => 'suite', 'name' => 'A-Name'),
    array('type' => 'suite', 'name' => 'C-Name'),
    array('type' => 'suite', 'name' => 'B-Name'),
);
$list = array_sort($list, 'name', SORT_ASC);
5

1 Answer 1

0

I see you found a solution but just in case I'll write my answer, maybe someone finds it useful

<?php
    $order_by = "asc";
    $list = array(
        array('type' => 'suite', 'name' => 'A-Name'),
        array('type' => 'suite', 'name' => 'C-Name'),
        array('type' => 'suite', 'name' => 'B-Name'),
    );
    usort($list, "customSort");

    function customSort($a, $b) {
        global $order_by;

        $compare = strcmp($a['name'], $b['name']);

        if($compare == 0) {
            return 0;
        } else if($compare > 0) {
            if($order_by == "asc") {
                return 1;
            } else {
                return -1;
            }
        } else if($compare < 0) {
            if($order_by == "asc") {
                return -1;
            } else {
                return 1;
            }
        }
    }

    echo "<pre>".print_r($list, true);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.