idealerror
idealerror

Reputation: 675

Moving single array to multi-dimension array

My problem.. I have a PHP array that looks like this:

[1013] => [1154]
[1013] => [1322]
[1154] => [1525]
[1525] => [1526]

How can I take that and move it to something like this:

[1013] => [1154] => [1525] => [1526]
[1013] => [1322]

So it sort of makes a tree that associates to the top level array item. I do not have control over how the data comes to me, it's generated through a third-party API and given to me just like that.

Logic: Client 1013 is the main account. Client 1154 is a client of 1013. Client 1322 is a client of 1013. Client 1525 is a client of 1154. I want to get it to a multi-dimension array so I can show this in a tree format.

Upvotes: 1

Views: 105

Answers (3)

Ralf
Ralf

Reputation: 1

Chris, you should have just emailed me first. :-p

$test_array = array('1','2','3','4','5','6');
$output_string = '';
for ($i = 0; $i < sizeof($test_array) -1; $i++)
{
    $output_string .= '{"'.$test_array[$i].'":';
}
$output_string .= $test_array[$i];
for ($i = 0; $i < sizeof($test_array)-1; $i++) { $output_string .= '}'; }
$new_array = json_decode($output_string, true);

var_dump($new_array);

Upvotes: 0

user657496
user657496

Reputation:

Here you go!:

<?php
// dataset
$clientset = array(
  array(1013, 1154),
  array(1013, 1322),
  array(1154, 1525),
  array(1525, 1526)
);

$children = array();

// make an array with children to see which nodes have none
foreach($clientset as $set) {
  if(!isset($children[$set[0]])) $children[$set[0]] = array($set[1]);
  else $children[$set[0]][] = $set[1];
}

// array with parents
$parents = array();
foreach($clientset as $set) {
  $parents[$set[1]] = $set[0];
}

// for each node with no children, begin the search!
foreach($clientset as $set) {
  if(!isset($children[$set[1]])) {
  echo getPath($set[1]).'</br>';
  }
}

// recursively search to parents and print them
function getPath($child) {
  global $parents;
  if($parents[$child]) {
    return (getPath($parents[$child]).' => '.$child);   
  } else return $child;
}
?>

This outputs:

1013 => 1322
1013 => 1154 => 1525 => 1526

The idea is to see which nodes have no children. Then, iterate through their parents. You probably don't need the output like it is right now, but I'm sure you can work it out this way. Enjoy!

Upvotes: 2

tijs
tijs

Reputation: 566

You can use array_walk php function to apply callback to each element of source array. Callback should create a new array according to your requirements. Callback function will take 2 parameters: value of current array element and it's key. Using that it's simple to build array you need.

Upvotes: 1

Related Questions