Create arrays according to "exploded" strings

Asked

Viewed 47 times

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 it’s just to give the example):

Array

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

How can I do that?

NOTE: The numbers may vary, as they come from dynamic records. I thought about creating several arrays manually, but I can’t, because they can vary at any time.

Any idea?

I tried so, but without results. I tried to explode each line using the "-" separator, but I couldn’t find an efficient way to group them:

foreach($arrayCategorias as $key => $val){
    $exploded = explode('-', $key);
    $results[$exploded[0]][$exploded[1]] = $val;
}

1 answer

3


Is 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 main keys reordered ([0], [1] ...), after the foreach can do:

$newArr = array_values($newArr);

DEMONSTRATION

  • Almost there, @Miguel! Can you adapt to an array without being multidimensional? ex: Dude, can you adapt this to a simpler array? $arrayCategories = array( '1-6', '1-7', '2-9', '3-2', '3-5' );

  • That, this is original format! It comes from the application. I passed the wrong example... I will fix.

  • 1

    Perfect @Miguel, thank you very much, and forgive the misconception of the example! Saved a life here! ;)

  • haha de nada @Maykelesser

  • @Maykelesser I made a small mistake, this line is more correct

  • with its adjustment, gave PARSE ERROR: Parse error: syntax error, Unexpected '[' in

  • @Maykelesser , you must have some syntax error: https://ideone.com/jpR6HI

  • 1

    I think that explode('-', $val)[0] does not work in some versions of PHP.

  • 1

    In this case @Maykelesser , put $num[0] in putting [0] where it explodes. Obgado @Augusto

  • Thanks @Augusto, I was going through everything here and I couldn’t find the problem! hahah, I use PHP 5.3.1. Thanks again, @Miguel!

Show 5 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.