7

百思不得其解: PHP 怎么把一维数组的键值转化为多维数组的键名

 3 years ago
source link: https://www.v2ex.com/t/827838
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

V2EX  ›  程序员

百思不得其解: PHP 怎么把一维数组的键值转化为多维数组的键名

  tellmeworld · 4 小时 13 分钟前 · 407 次点击

比如$arr=array('a','b','c','d'); 长度不固定;

要变成$arr['a']['b']['c']['d'], 按照顺序的;

请问有啥办法?

10 条回复    2022-01-12 16:38:43 +08:00

dajj

dajj      4 小时 6 分钟前

太简单了, 你再想想

FaceBug

FaceBug      4 小时 6 分钟前

那你的值是什么呢? null ?

tellmeworld

tellmeworld      4 小时 1 分钟前

@FaceBug 后续有判断的,是判断如果一维数组$arr 不为空,就变成多维数组,并赋值一个特定的数给它。

BJL

BJL      3 小时 57 分钟前   ❤️ 1

$src = ['a','b','c','d'];

$output_v = "";

for($i = count($src) - 1;$i >= 0;$i--){
$v = $src[$i];
$v_prev = $src[$i + 1] ?? "";
$output[$v] = $output ?? $output_v;
unset($output[$v_prev]);
}
echo json_encode($output);

tellmeworld

tellmeworld      3 小时 56 分钟前

厉害,我刚想到可能先转化为 json 字符串形式,然后再转换,你已经写好了

q792602257

q792602257      3 小时 55 分钟前   ❤️ 1

仅供参考
```php
/**
* @var string[] 必须是能作为数组键的值
*/
$arr = array("a", "b", "c", "d", "e");
$newArr = array();
// 引用新的数组
$newArrPointer = &$newArr;
while (sizeof($arr) > 0) {
// 移出第一个元素,作为键名
$key = array_shift($arr);
// 对上一个引用,做修改操作
$newArrPointer[$key] = array();
// 重新引用新的数组
$newArrPointer = &$newArrPointer[$key];
}
// 如果需要赋值,在这里赋值
$newArrPointer = 777;
// 释放引用
unset($newArrPointer);
print_r($newArr);
```

BJL

BJL      3 小时 52 分钟前

@tellmeworld 楼上那个比较好

FaceBug

FaceBug      3 小时 34 分钟前

@tellmeworld 是我理解错了

不过这和 json 有什么关系

justrand

justrand      3 小时 21 分钟前

@tellmeworld 你需要的结果是这样的?
~~~php
array(1) {
["a"]=>
array(1) {
["b"]=>
array(1) {
["c"]=>
array(1) {
["d"]=>
array(1) {
["e"]=>
int(777)
}
}
}
}
}

FaceBug

FaceBug      3 小时 19 分钟前

$src = ['a', 'b', 'c', 'd'];
$output = "";
while (count($src) > 0) {
$tmp = [];
$output = $tmp[array_pop($src)] = $output;
$output = $tmp;
}
print_r($output);

Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK