Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 将单个阵列移动到多维阵列_Php_Arrays_Multidimensional Array - Fatal编程技术网

Php 将单个阵列移动到多维阵列

Php 将单个阵列移动到多维阵列,php,arrays,multidimensional-array,Php,Arrays,Multidimensional Array,我的问题。。我有一个PHP数组,如下所示: [1013] => [1154] [1013] => [1322] [1154] => [1525] [1525] => [1526] [1013] => [1154] => [1525] => [1526] [1013] => [1322] 我怎样才能把它移到像这样的地方: [1013] => [1154] [1013] => [1322] [1154] => [1525] [15

我的问题。。我有一个PHP数组,如下所示:

[1013] => [1154]
[1013] => [1322]
[1154] => [1525]
[1525] => [1526]
[1013] => [1154] => [1525] => [1526]
[1013] => [1322]
我怎样才能把它移到像这样的地方:

[1013] => [1154]
[1013] => [1322]
[1154] => [1525]
[1525] => [1526]
[1013] => [1154] => [1525] => [1526]
[1013] => [1322]
所以它有点像一棵树,与顶级数组项相关联。我无法控制数据是如何传递给我的,它是通过第三方API生成的,并以这种方式提供给我


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

您可以使用
array\u walk
php函数对源数组的每个元素应用回调。回调应该根据您的要求创建一个新数组。回调函数将接受两个参数:当前数组元素的值和它的键。使用它可以轻松构建所需的阵列。

给你

<?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;
}
?>
其目的是查看哪些节点没有子节点。然后,重复他们的父母。您可能不需要像现在这样的输出,但我相信您可以通过这种方式解决它。享受吧

克里斯,你应该先给我发电子邮件-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);
$test_array=array('1','2','3','4','5','6');
$output_string='';
对于($i=0;$i
应该创建什么逻辑?您必须遍历数组并将其插入到新数组中。过去几个小时我一直在尝试遍历它,但运气不佳。从字面上讲,经历了大量不同的方法。@DainisAbols这样想。客户1013是主要客户。客户1154是1013的客户。客户1322是1013的客户。客户1525是1154的客户。我想把它放到一个多维数组中,这样我就可以用树的格式来显示它。我懒得去测试它,但是这个()可能会让你开始。我不太确定这会给我正确的结果,你有没有一个示例代码块来演示类似的结果?