1

I have an array like this:

array (size=3)
  4 => 
    array (size=3)
      'id' => int 4
      'parentId' => int 3
      'name' => string 'z' (length=4)
  5 => 
    array (size=3)
      'id' => int 4
      'parentId' => int 3
      'name' => string 'a' (length=4)
  9 => 
    array (size=3)
      'id' => int 4
      'parentId' => int 3
      'name' => string 'd' (length=4)

And i have to sort this array ascending by name! The goal is, to make the array to the following structure:

array (size=3)
  5 => 
    array (size=3)
      'id' => int 4
      'parentId' => int 3
      'name' => string 'a' (length=4)
  9 => 
    array (size=3)
      'id' => int 4
      'parentId' => int 3
      'name' => string 'd' (length=4)
  4 => 
    array (size=3)
      'id' => int 4
      'parentId' => int 3
      'name' => string 'z' (length=4)

Do you guys have any smart solutions? I've tried to save the keys and the name belongs to the key in a new array, and iterate the ksort'ed array once again, and set the new position:

    // Placeholder
    $categoryContainer = array();

    // Iterate all categories
    foreach(self::$categories as $key => $category) {
        $categoryContainer[$category['name']] = $key;
    }

    // Resort by key (category name!)
    ksort($categoryContainer);
Tyralcori
  • 1,079
  • 13
  • 33

1 Answers1

2

You can use usort http://php.net/manual/en/function.usort.php

function cmp($a, $b)
{
    if ($a == $b) {
        return 0;
    }
    return ($a['name'] < $b['name']) ? -1 : 1;
}

usort($array, "cmp");
Mex
  • 1,011
  • 7
  • 16