我尝试构建一个数组。我不想写像$ array [3] [5] [8] = []这样的东西。因为第一个数组的计数可以改变,所以它在3中也可以是9或12.这些值也可以改变,但它们总是唯一的数字。我希望有人知道更好的方法。谢谢。
// First Array, which I have. The count and the content can change.
array(3) {
[0]=>
string(1) "3"
[1]=>
string(1) "5"
[2]=>
string(1) "8"
}
// Second Array, thats the goal.
array(1) {
[3]=>
array(1) {
[5]=>
array(1) {
[8]=>
array(0) {
}
}
}
}
答案 0 :(得分:1)
此代码将解决您的问题:
$array = [3,5,8,9]; // your first array
$newArray = null;
foreach ($array as $value) {
if($newArray === null) {
$newArray[$value] = [];
$ref = &$newArray[$value];
}
else {
$ref[$value] = [];
$ref = &$ref[$value];
}
}
$ newArray - 保存你想要的结果
答案 1 :(得分:1)
$array1=array(3,5,8);
$array2=array();
for($i=count($array1);$i>0;$i--){
$temp=array();
$temp[$array1[$i-1]]=$array2;
$array2=$temp;
}
答案 2 :(得分:0)
$subject = $array = []; foreach($input as $key){ $subject[$key] = []; // create empty array $subject =& $subject[$key]; // set reference to child // Now $subject is the innermost array. // Editing $subject will change the most nested value in $array }