1

私の問題..次のようなPHP配列があります。

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

どうすればそれを取り、次のようなものに移動できますか:

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

したがって、最上位の配列項目に関連付けられるツリーが作成されます。データがどのように私に届くかを制御することはできません。データはサードパーティの API を介して生成され、そのまま私に渡されます。

ロジック:クライアント 1013 がメイン アカウントです。クライアント 1154 は 1013 のクライアントです。クライアント 1322 は 1013 のクライアントです。クライアント 1525 は 1154 のクライアントです。これをツリー形式で表示できるように多次元配列にしたいと考えています。

4

3 に答える 3

2

どうぞ!:

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

アイデアは、どのノードに子がないかを確認することです。次に、親を反復処理します。現在のような出力はおそらく必要ありませんが、この方法で解決できると確信しています。楽しみ!

于 2012-08-01T12:10:39.917 に答える
1

php 関数を使用array_walkして、ソース配列の各要素にコールバックを適用できます。コールバックは、要件に従って新しい配列を作成する必要があります。コールバック関数は、現在の配列要素の値とそのキーの 2 つのパラメーターを取ります。それを使用すると、必要な配列を簡単に構築できます。

于 2012-08-01T12:04:13.543 に答える
0

クリス、あなたは最初に私にメールを送るべきだった。:-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);
于 2012-08-01T13:30:32.593 に答える