Rasmus Styrk
Rasmus Styrk

Reputation: 1346

convert string to array

I have this string: test1__test2__test3__test4__test5__test6=value

There could be any number of test-keys.

I want to write a function that can turn the string above into an array

$data[test1][test2][test3][test4][test5][test6] = "value";

Is this possible?

Upvotes: 1

Views: 335

Answers (5)

Felix Kling
Felix Kling

Reputation: 816334

Yes it is possible:

list($keys, $value) = explode('=', $str);
$keys = explode('__', $keys);

$t = &$data;
$last = array_pop($keys);

foreach($keys as $key) {
    if(!isset($t[$key]) || !is_array($t[$key])) {
        // will override non array values if present
        $t[$key] = array();
    }
    $t = &$t[$key];
}

$t[$last] = $value;

DEMO

Reference: list, explode, =&, is_array, array_pop

Upvotes: 3

Ferdinand Beyer
Ferdinand Beyer

Reputation: 67137

$data = array();

// Supposing you have multiple strings to analyse...
foreach ($strings as $string) {
    // Split at '=' to separate key and value parts.
    list($key, $value) = explode("=", $string);

    // Current storage destination is the root data array.
    $current =& $data;

    // Split by '__' and remove the last part
    $parts = explode("__", $key);
    $last_part = array_pop($parts);

    // Create nested arrays for each remaining part.
    foreach ($parts as $part)
    {
        if (!array_key_exists($part, $current) || !is_array($current[$part])) {
            $current[$part] = array();
        }
        $current =& $current[$part];
    }

    // $current is now the deepest array ($data['test1']['test2'][...]['test5']).
    // Assign the value to his array, using the last part ('test6') as key.
    $current[$last_part] = $value;
}

Upvotes: 2

SteeveDroz
SteeveDroz

Reputation: 6136

I suppose it is...

$string = "test1__test2__test3__test4__test5__test6=value";
$values = explode('=',$string);
$indexes = explode('__',$values[0]);
$data[$indexes[0]][$indexes[1]][$indexes[2]][$indexes[3]][$indexes[4]][$indexes[5]] = $values[1];

Upvotes: 0

ajreal
ajreal

Reputation: 47321

$str = ...;
eval( str_replace('__', '][', 
preg_replace('/^(.*)=(.*)$/', '\$data[$1]=\'$2\';', $str)) );

easier way, assuming the $str is trustable data

Upvotes: 1

Emil Vikström
Emil Vikström

Reputation: 91912

function special_explode($string) {
  $keyval = explode('=', $string);
  $keys = explode('__', $keyval[0]);
  $result = array();

  //$last is a reference to the latest inserted element                         
  $last =& $result;
  foreach($keys as $k) {
    $last[$k] = array();
    //Move $last                                                                
    $last =& $last[$k];
  }

  //Set value                                                                   
  $last = $keyval[1];
  return $result;
}

//Test code:
$string = 'test1__test2__test3__test4__test5__test6=value';
print_r(special_explode($string));

Upvotes: 3

Related Questions