Search code examples
phparrayssortingstable-sort

Stable sort an array of pipe-delimited strings only by the leading value


I have an array that contains entries that themselves contain two types of entries.

For simplicity sake, let's say that the entries are like this:

a|1
b|4
a|2
c|5
b|3

etc.

In fact they represent categories and subcategories in my database.

I will use explode to break these entries into letters and digits.

The question is: I want to group them by category.

What's the easiest way to create a multilevel array, which could be sorted by letters:

a|1
a|2
b|4
b|3
c|5

?


Solution

  • How about something like this?

    $input  = array('a|1','b|4','a|2','c|5','b|3');
    $output = array();
    
    foreach($input as $i){
    
        list($key,$val) = explode("|",$i);
        $output[$key][] = $val;
    
    }
    

    Output:

    Array
    (
    [a] => Array
        (
            [0] => 1
            [1] => 2
        )
    
    [b] => Array
        (
            [0] => 4
            [1] => 3
        )
    
    [c] => Array
        (
            [0] => 5
        )
    
    )