Search code examples
phparraysmultidimensional-arraygroupingprefix

Group array values by prefix


I have an array, something like this:

Array
    (
        [0] => Size: tiny
        [1] => Size: small
        [2] => Size: big
        [3] => Colour: yellow
        [4] => Colour: black
        [5] => Colour: blue
        [6] => Length: short
        [7] => Length: long
    )

What I would like to do is, go thru each field, fich I did with foreach, used explode to divide each array so I have now the first attribute in one array (size, coluor, lenght .. etc) and the other value in other field.

Outcome Im hoping for is actually finding, if all the attributes (size, colour ...) are the same, or they are different. If they are different, I'd like to put thme in arrays ... presumably this example would return array like this:

Array
(
    [0] => Array
        (
            [0] => Size: tiny
            [1] => Size: small
            [2] => Size: big
        )

    [1] => Array
        (
            [0] => Colour: yellow
            [1] => Colour: black
            [2] => Colour: blue
        )

    [2] => Array
        (
             [0] => Length: short
             [1] => Length: long
        )

)

Solution

  • <?php
    $array = Array
        (
            '0' => 'Size: tiny',
            '1' => 'Size: small',
            '2' => 'Size: big',
            '3' => 'Colour: yellow',
            '4' => 'Colour: black',
            '5' => 'Colour: blue',
            '6' => 'Length: short',
            '7' => 'Length: long'
        );
    
        $map = array();
        foreach($array as &$value)
        {
            $keyV = explode(': ',$value);
                $map[$keyV[0]][] = $value;
    
        }
    
        $final = array_values($map); // throw away the keys
    
        var_dump($final);
    

    Gives exactly what you want:

    array(3) {
      [0]=>
      array(3) {
        [0]=>
        string(10) "Size: tiny"
        [1]=>
        string(11) "Size: small"
        [2]=>
        string(9) "Size: big"
      }
      [1]=>
      array(3) {
        [0]=>
        string(14) "Colour: yellow"
        [1]=>
        string(13) "Colour: black"
        [2]=>
        string(12) "Colour: blue"
      }
      [2]=>
      array(2) {
        [0]=>
        string(13) "Length: short"
        [1]=>
        string(12) "Length: long"
      }
    }