2

Input:

$sql = array(

    array("id"=>"47", "name"=>"Jason", "device"=>"idevice"),
    array("id"=>"49", "name"=>"uniKornn", "device"=>"idevice"),
    array("id"=>"50", "name"=>"jacob", "device"=>"idevice")
)

Output:

$sql = array(

    array("id"=>"50", "name"=>"jacob", "device"=>"idevice"),
    array("id"=>"47", "name"=>"Jason", "device"=>"idevice"),
    array("id"=>"49", "name"=>"uniKornn", "device"=>"idevice")
)

I want to set the order of the array $sql, by name, and case-insensitive.

3
  • 1
    And what have you tried? Commented Jan 26, 2014 at 16:21
  • I've tried using sort($sql) but that didn't work... Commented Jan 26, 2014 at 16:21
  • How about ksort($sql) Commented Jan 26, 2014 at 16:23

2 Answers 2

5
function build_sorter($key) {
    return function ($a, $b) use ($key) {
        return strnatcmp($a[$key], $b[$key]);
    };
}

usort($sql, build_sorter('name'));

EDIT: For case-insensitive:

Option 1:

function build_sorter($key) {
    return function ($a, $b) use ($key) {
        return strnatcasecmp($a[$key], $b[$key]);
    };
}

usort($sql, build_sorter('name'));

Option 2:

function build_sorter($key) {
    return function ($a, $b) use ($key) {
        return strnatcmp(strtolower($a[$key]), strtolower($b[$key]));
    };
}

usort($sql, build_sorter('name'));

Full Code:

<?php

$sql = array(
    array("id"=>"47", "name"=>"Jason", "device"=>"idevice"),
    array("id"=>"49", "name"=>"uniKornn", "device"=>"idevice"),
    array("id"=>"50", "name"=>"jacob", "device"=>"idevice")
);

function build_sorter($key) {
    return function ($a, $b) use ($key) {
        return strnatcmp(strtolower($a[$key]), strtolower($b[$key]));
    };
}

usort($sql, build_sorter('name'));

foreach ($sql as $item) {
    echo $item['id'] . ', ' . $item['name'] .', ' . $item['device'] . "\n";
}

?>
Sign up to request clarification or add additional context in comments.

1 Comment

This works, but it is case-sensitive. It orders by A-Z a-z. I want it to be case-insensitive
-1

Or short version for strings

function cmp($a, $b)
{
     return strcmp($a["name"], $b["name"]);
 }

usort($array, "cmp");

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.