0

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

?

Jan Dragsbaek
  • 8,078
  • 2
  • 26
  • 46
Uno Mein Ame
  • 1,060
  • 5
  • 16
  • 29
  • something similar http://stackoverflow.com/questions/2189626/php-how-to-group-a-multidimensional-array-by-a-particular-value – cristian Dec 13 '11 at 09:55

3 Answers3

2

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
    )

)
Kokos
  • 9,051
  • 5
  • 27
  • 44
  • this looks great. is there a way to access the values for keys, too? I mean - how would i know to use 'a', 'b', and 'c' unless I know these values? – Uno Mein Ame Dec 13 '11 at 10:10
0
<?php

$your_array = array();

$your_array[a] = array('1','2','3');
$your_array[b] = array('4','5','6');

print_r($your_array);

?>
njmu83
  • 304
  • 2
  • 10
0

I take it that your entries are strings (relying on the fact that you want to use explode() on them).

If so you can simply sort the array by using sort($array), and then iterate on that array and explode the values and put them in another array, which will be sorted by the previous array's order.

MeLight
  • 5,454
  • 4
  • 43
  • 67