0

How would I sort or iterate a multi-dimensional array so that it forms a tree like structure (all children after each parent) such as:

Parent #1
Child #1
Child #2

Parent #2
Child #1

Parent #3
Child #1
Child #2

This is an example Array. It is important to note that the array is initially unsorted (items and their children do not appear in any specific order).

Array (
[0] => Array
    (
        [id] => 1 
        [content] => Parent #1 
    )
[1] => Array
    (
        [id] => 2
        [content] => Parent #2
    )
[2] => Array
    (
        [id] => 3
        [content] => Parent #3
    )
[3] => Array
    (
        [parent] => 1
        [content] => Child #1
    )
[4] => Array
    (
        [parent] => 1
        [content] => Child #2
    )
[5] => Array
    (
        [parent] => 3
        [content] => Child #2
    )
[6] => Array (
        [parent] => 3
        [content] => Child #1
    )
[7] => Array (
        [parent] => 2
        [content] => Child #1
    )
)

I apologize if I am completely wrong or asking something that is impossible. I have tried using usort but I have been unable to figure out the proper logic.

4

1 回答 1

0
<?php
$array = array(
           array(
             'id' => 1,
             'num' => 6,
             'color' => 'green'
),

           array(
             'id' => 4,
             'num' => 5,
             'color' => 'red'
)
           );
$nk = new_sort($array,'color','asc');
print_r($nk);

$nk = new_sort($array,'num','desc');
print_r($nk);
function new_sort($array_data, $key, $orderby = 'asc')
{
  $na = $rv = array();

  foreach ($array_data as $k => $n) {
    $na[$k] = $n[$key];
  }
  $orderby == 'asc' ? asort($na) : arsort($na);
  foreach ($na as $nk => $nv) {
    $rv[] =  $array_data[$nk];
  }

  return $rv;
}
于 2013-03-06T02:19:57.077 回答