我尝试构建一个数组。我不想写类似 $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) {
}
}
}
}
最佳答案
此代码将解决您的问题:
$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 - 保存您想要的结果
关于php - 在 PHP 中使用另一个数组构建多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40397341/