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;
}
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' );
– Maykel Esser
That, this is original format! It comes from the application. I passed the wrong example... I will fix.
– Maykel Esser
Perfect @Miguel, thank you very much, and forgive the misconception of the example! Saved a life here! ;)
– Maykel Esser
haha de nada @Maykelesser
– Miguel
@Maykelesser I made a small mistake, this line is more correct
– Miguel
with its adjustment, gave PARSE ERROR: Parse error: syntax error, Unexpected '[' in
– Maykel Esser
@Maykelesser , you must have some syntax error: https://ideone.com/jpR6HI
– Miguel
I think that
explode('-', $val)[0]
does not work in some versions of PHP.– Augusto
In this case @Maykelesser , put
$num[0]
in putting[0]
where it explodes. Obgado @Augusto– Miguel
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!
– Maykel Esser