Jump to content

[SOLVED] how do you sort this array


asmith

Recommended Posts

Hi,

 

I have an array like this  :

 

$a = array(

 

1 => 0

2 => 0

32 => 0

34 => 1

23 => 32

45 => 1

...

);

 

The key is the board ID and its value is the board parent. For example boards 1,2,32 are the main board so their parent is 0. Board 34 is first child of board 1 or board 45 is first child of board 34 and second child of board 1.

 

I want to sort it, so that a main board start first, then its first child (then its childs of the first child), then second child.  when finished, next main board (next board with parent 0).

 

So that with a loop I could do an html menu. (with html list maybe)

 

How can I sort it?

 

p.s like this array, they are recorded in the database. each are a row in a table. maybe 1 nice query for mysql instead of sorting array? I couldn't find one query for that.

 

 

Link to comment
https://forums.phpfreaks.com/topic/147128-solved-how-do-you-sort-this-array/
Share on other sites

That's because you can't do that with one query. Storing tree structures in a flat table is always tricky (well... storing is piece of cake, but retrieving data is tricky ;) ) It will basically require you to either recursively loop through each branch, or store the data from MySQL into a tree like data structure.

 

Array(
0 => Array (
  1 => Array(
   34,
   45
  ),
  2,
  32 => Array(
   23
  )
)
)

Doesn't use your key => value structure, but it is based on a parent/child array:

$items = array(
        array('id' => '1', 'pid' => '0'),
        array('id' => '2', 'pid' => '0'),
        array('id' => '3', 'pid' => '0'),
        array('id' => '4', 'pid' => '1'),
        array('id' => '5', 'pid' => '1'),
        array('id' => '6', 'pid' => '1'),
        array('id' => '7', 'pid' => '2'),
        array('id' => '8', 'pid' => '4')
);

function showLevel($items,$parent) {
    $ulSet = False;
    foreach ($items as $item) {
        if ($item['pid'] == $parent) {
            if (!$ulSet) {
                $ulSet = True;
                echo '<ul>';
            }
            echo '<li>'.$item['id'].'</li>';
            showLevel($items,$item['id']);
        }
    }
    if ($ulSet) { echo '</ul>'; }
}

showLevel($items,'0');

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.