phpchap
phpchap

Reputation: 41

string to associative array conversion

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...

Upvotes: 1

Views: 370

Answers (2)

Kévin Bibollet
Kévin Bibollet

Reputation: 3623

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 ) ) ) )

Upvotes: 0

LF-DevJourney
LF-DevJourney

Reputation: 28559

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);

Upvotes: 1

Related Questions