Search code examples
phparrayssortingmultidimensional-arraysequential

Sort a 2d array by recurring ascending sequences of a column's values


I have an Array that I need to sort, I will post an example for better understanding. This is my unsorted Array:

[0] => Array
    (
        [title] => This is some title
        [catid] => 1
    )    
[1] => Array
    (
        [title] => This is some title
        [catid] => 1
    )
[2] => Array
    (
        [title] => This is some title
        [catid] => 2
    )    
[3] => Array
    (
        [title] => This is some title
        [catid] => 2
    )

I need to re-sort it like this:

[0] => Array
    (
        [title] => This is some title
        [catid] => 1
    )    
[1] => Array
    (
        [title] => This is some title
        [catid] => 2
    )
[2] => Array
    (
        [title] => This is some title
        [catid] => 1
    )    
[3] => Array
    (
        [title] => This is some title
        [catid] => 2
    )

I'll have more that two categories and I need to select one item per category so if I have 3 categories, my catid in that case will be sorted like this:

catid: 1, 2, 3, 1, 2, 3


Solution

  • Here's my take:

    /** just generating some data, not part of script **/
    $originalArray = array();
    $title = range('a','z');
    for ($x=0;$x<20;$x++) {
      shuffle($title);
      $originalArray[] = array(
        'title' => implode(array_slice($title,0,rand(4,9))),
        'catid' => rand(1,3)
      );
    }
    /** end generating data **/
    
    
    $tempArray = array();
    foreach ($originalArray as $array) {
      $tempArray[$array['catid']][] = $array['title'];
    }
    ksort($tempArray);
    
    $newArray = array();
    while (count($tempArray)>0) {
      foreach ($tempArray as $mKey => &$mArray) {
        if (count($mArray)>0)
          $newArray[] = array('title'=>array_shift($mArray),'catid'=>$mKey);
      }
      $tempArray = array_filter($tempArray);
    }