1

Say I have an array with keys representing id and values representing parent:

4  => 0
2  => 0
5  => 2
6  => 5
8  => 0
9  => 0
10 => 8
12 => 0
13 => 0
14 => 0
18 => 7
19 => 18
20 => 19
21 => 20
22 => 21
23 => 22
24 => 23
28 => 20
7  => 5

You could also read this as an object:

  { 
   id     : 4,
   parent : 0
  } // etc...

The multidimensional array I'd want to achieve from this would be:

4  => 0
2  => 5  
        => 6
        => 7
            => 18
                 => 19
                      => 20
                           => 21
                                 => 22
                                       => 23
                                             => 24
                           => 28
8  => 10
9  => 0
12 => 0
13 => 0
14 => 0

How would I go about doing this?

3
  • Seems like Graph (in Computer Science)? Commented Jul 20, 2012 at 9:30
  • certainly smells like homework Commented Jul 20, 2012 at 9:31
  • it looks "weight" in an sorted array Commented Jul 20, 2012 at 9:34

1 Answer 1

3

If you write a little helper function to rework your data to a structure similar to:

$input = array(
  array('id' => '4', 'parent' => '0'),
  // ...
);

which could be achieved with something like:

$data = array_map(function ($entry) {
  list($id, $parent) = array_map('trim', explode('=>', $entry));
  return array(
    'id' => $id,
    'parent' => $parent
  );
}, explode("\n", $data));

you could then use a function I used in a similar question:

function flatToNested($d, $r = 0, $p = 'parent', $k = 'id', $c = 'children') {
  $m = array();
  foreach ($d as $e) {
    isset($m[$e[$p]]) ?: $m[$e[$p]] = array();
    isset($m[$e[$k]]) ?: $m[$e[$k]] = array();
    $m[$e[$p]][] = array_merge($e, array($c => &$m[$e[$k]]));
  }
  return $m[$r];
}

to produce a nested array with:

$nested = flatToNested($data);

demo: http://codepad.viper-7.com/HAZxaA

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

3 Comments

What if the values are strings, i.e. id=>'node-4',parent='node-0', instead of id=4 etc..? How could I modify this function?
@Patrick I don't think that this should be a problem, as long as they are unique flatToNested would handle it correctly.
@Patrick try: $nested = flatToNested($doesntwork, 'node0'); The $r paramater to flatToNested selects the root node to return.

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.