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

?

2
  • something similar stackoverflow.com/questions/2189626/… Commented Dec 13, 2011 at 9:55
  • This question is not very clear because the input and output "array" data is presented as pipe-delimited lines of a multiline string. Commented Jan 15 at 23:11

3 Answers 3

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
    )

)
Sign up to request clarification or add additional context in comments.

1 Comment

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?
0
<?php

$your_array = array();

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

print_r($your_array);

?>

1 Comment

sorry, to response to the question print_r(arsort(your_array));
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.