Create arrays according to "exploded" strings

2

I have the following array:

Array
(
    [0] => 1-6
    [1] => 1-7
    [2] => 2,9
)

I would like to group it according to their initial number.

Example result (I'm not sure of this syntax, but just to give the example):

Array

(
    [0] => Array
    (
        [] => 1-6,
        [] => 1-7
    )
    [1] => Array
    (
        [] => 2-9
    )
)

How can I do this?

NOTE: Numbers can vary because they come from dynamic records. I thought about creating several arrays manually, but I can not because they can vary at any time.

Any ideas?

I tried this, but no results. I tried to blow each line using the "-" tab, but I did not find an efficient way to group them:

foreach($arrayCategorias as $key => $val){
    $exploded = explode('-', $key);
    $results[$exploded[0]][$exploded[1]] = $val;
}
    
asked by anonymous 17.02.2017 / 18:30

1 answer

3

It will be this:

$arrayCategorias = array( '1-6', '1-7', '2-9', '3-2', '3-5' );
$newArr = array();
foreach($arrayCategorias as $key => $val) {
    $num = explode('-', $val)[0];
    $newArr[$num][] = $val;
}

echo '<pre>', print_r($newArr), '</pre>';

output:

Array
(
    [1] => Array
        (
            [0] => 1-6
            [1] => 1-7
        )

    [2] => Array
        (
            [0] => 2-9
        )

    [3] => Array
        (
            [0] => 3-2
            [1] => 3-5
        )

)

If you want the reordered primary keys ( [0] , [1] ...), then foreach you can do:

$newArr = array_values($newArr);

STATEMENT

    
17.02.2017 / 18:39