如何从数组值生成多维数组
Posted
技术标签:
【中文标题】如何从数组值生成多维数组【英文标题】:how to generate multidimensional array from array value 【发布时间】:2018-07-12 20:35:27 【问题描述】:我是 php 的新手,我卡在了一些实际上我需要从数组值生成多维数组的地方。 例如,我的数组就是这样,记住所有数组和值都是动态的
array(
0 => array(
0 => "college"
1 => "student"
2 => "contact"
),
1 => array(
0 => "college"
1 => "parents"
2 => "contact"
),
2 => array(
0 => "school"
1 => "parents"
2 => "contact"
),
3 => array(
0 => "school"
1 => "student"
2 => "contact"
))
我想要这样的结果
0 => array (
"college" => array(
"student" => array (
"contact" => array (
"address" => "address_value"
)
),
"parents" => array (
"contact" => array (
"address" => "address_value"
)
),
),
"school" => array(
"student" => array (
"contact" => array (
"address" => "address_value"
)
),
"parents" => array (
"contact" => array (
"address" => "address_value"
)
),
)),
我想生成多维数组,直到数组值和最后一个数组有一些值
任何人都可以以标准方式帮助我。 帮助将不胜感激.. 提前致谢
【问题讨论】:
array:5
是什么意思?
@Syscall 只是拼写错误
【参考方案1】:
试试这个:
<?php
function group($a, $level, $previous = '')
$b = [];
for( $i = 0, $n = count($a); $i < $n; ++$i )
if( $level > 0 && $a[$i][$level-1] !== $previous )
continue;
$key = $a[$i][$level];
$b[$key] = [];
if( array_key_exists($level+1, $a[$i]) )
$b[$key] = group($a, $level+1, $key);
return $b;
print_r(group($a, 0));
输出:
Array(
[college] => Array (
[student] => Array (
[contact] => Array ()
)
[parents] => Array (
[contact] => Array ()
)
)
[school] => Array (
[student] => Array (
[contact] => Array ()
)
[parents] => Array (
[contact] => Array ()
)
)
)
使用@AlivetoDie 示例:
Array (
[college] => Array (
[student] => Array (
[contact] => Array ()
)
[parents] => Array (
[contact] => Array ()
)
)
[school] => Array (
[parents] => Array (
[contact] => Array ()
)
[student] => Array (
[contact] => Array ()
)
[data] => Array (
[contact] => Array()
)
)
)
【讨论】:
在以下情况下将不起作用:-$a = array( 0 => array( 0 => "college", 1 => "student", 2 => "contact" ), 1 => array( 0 => "college", 1 => "parents", 2 => "contact" ), 2 => array( 0 => "school", 1 => "parents", 2 => "contact" ), 3 => array( 0 => "school", 1 => "student", 2 => "contact" ), 4 => array( 0 => "school", 1 => "data", 2 => "contact" ) );
现在看来是正确的。但需要用不同的结构+值进行检查。(这是OP任务,不是我的)。+1
@myxobek 当时我只通过$a = array(0 => "college",1 => "student",2 => "contact");
时,它向我展示了array_key_exists() expects parameter 2 to be array, string given
,因为当时我只通过了数组。有没有其他方法可以解决?
@RyanDen 函数期望您的数组与您在问题描述中提供的数组相似。注释中的数组与描述中的数组不相似。当您提供 $a = array(0 => array(0 => "college",1 => "student",2 => "contact"));
时它应该可以工作
@myxobek 好的,知道了,我可以正确传递数组。谢谢您的回复以上是关于如何从数组值生成多维数组的主要内容,如果未能解决你的问题,请参考以下文章