string to associative array conversion

▼魔方 西西 提交于 2020-01-03 03:25:13

问题


I've been struggling with this for a few days and wanted to throw it out there and see if someone has any ideas.

Basically I have a string e.g

1) "/0/bar"

2) "/build/0/foo/1"

and need to convert this into a multidimensional array

1) $result[0][bar] 
2) $result[build][0][foo][1]

So far I've tried:

$query = "/build/0/foo/1";
$queryAr = [];
$current = &$queryAr;
$keys = explode("/", $query);

foreach($keys as $key) {
  @$current = &$current[$key];
}

$current = $value;

quieting the output is a pretty hacky way to achive this...


回答1:


You need to trim the first / of the string. live demo.

<?php
$query = "/build/0/foo/1";
$queryAr = [];
$current = &$queryAr;
$keys = explode("/", trim($query, '/'));

foreach($keys as $key) {
  @$current = &$current[$key];
}

$current = $value;
print_r($queryAr);



回答2:


I tried a recursive function version:

$query = "/build/0/foo/1";
print_r($result = buildNestedArray(explode('/', trim($query, '/'))));

function buildNestedArray($keys)
{
    $k = current($keys);

    $result = [$k => 'DONE'];
    array_shift($keys);
    if (sizeof($keys) > 0) { $result[$k] = buildNestedArray($keys); }

    return $result;
}

output: Array ( [build] => Array ( [0] => Array ( [foo] => Array ( [1] => DONE ) ) ) )



来源:https://stackoverflow.com/questions/45504040/string-to-associative-array-conversion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!