将单个数组移动到多维数组


Moving single array to multi-dimension array

我的问题。。我有一个PHP数组,看起来像这样:

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

我怎么能把它移到这样的地方:

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

因此,它在某种程度上生成了一个与顶级数组项相关联的树。我无法控制数据是如何到达我的,它是通过第三方API生成的,并像那样提供给我。

逻辑:客户端1013是主帐户。客户端1154是1013的客户端。客户端1322是1013的客户端。客户端1525是1154的客户端。我想把它放到多维数组中,这样我就可以用树的格式显示它。

开始吧!:

<?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;
}
?>

该输出:

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

其想法是查看哪些节点没有子节点。然后,通过他们的父母进行迭代。你可能不需要像现在这样的输出,但我相信你可以用这种方式解决它。享受

您可以使用array_walk php函数将回调应用于源数组的每个元素。回调应该根据您的需求创建一个新的数组。回调函数将接受两个参数:当前数组元素的值和它的键。使用它可以简单地构建所需的数组。

Chris,你应该先给我发邮件-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);