S R
S R

Reputation: 167

String (literal array) to Array conversion

I have a string of the form:

string '["a"=>[10,20,30,40=>"Forty"],"b"=>[100,200,300,400=>"Four Hundred"],"c"=>[15]]' (length=78)

I need to convert this directly into an array as

array (size=3)
  'a' => 
    array (size=4)
      0 => int 10
      1 => int 20
      2 => int 30
      40 => string 'Forty' (length=5)
  'b' => 
    array (size=4)
      0 => int 100
      1 => int 200
      2 => int 300
      400 => string 'Four Hundred' (length=12)
  'c' => 
    array (size=1)
      0 => int 15

I have tried parse_str and json_encpde/decode and eval, but none of them see the variable as anything other than a string. Please help!

Upvotes: 2

Views: 1857

Answers (2)

Loupax
Loupax

Reputation: 4914

One way to do it would be to just eval the thing

$string = '["a"=>[10,20,30,40=>"Forty"],"b"=>[100,200,300,400=>"Four Hundred"],"c"=>[15]]';
$array = eval("return $string");
print_r($array);

Keep in mind though that both of these solutions actually evaluate PHP code that you didn't write yourself. If you can, I'd suggest storing this data as JSON or using serialize_array() instead

Could not make this example to work, leaving it for archive purposes or for somebody else to give a try

Can't test it right now but one of these might be able to help you IF you run a PHP version that supports the [] array notation.

$string = '["a"=>[10,20,30,40=>"Forty"],"b"=>[100,200,300,400=>"Four Hundred"],"c"=>[15]]';
file_put_contents('php://memory', $string);
$array = include 'php://memory';
print_r($array);

Upvotes: 1

senthil
senthil

Reputation: 324

Try this hope will help this.    
$input_string =  '["a"=>[10,20,30=>"test",40=>"Forty"],"b"=>[100,200,300,400=>"Four Hundred"],"c"=>[15]]'."<br/>";
    $s1 = str_replace('],','-',str_replace(']]','',str_replace('[','',$input_string)));
    $s2 = explode("-",$s1);
    foreach ($s2 as $key => $value) {
        $s3[] = explode("=>",str_replace('=>"','-"',$value));
        $s4[$s3[$key][0]] = $s3[$key][1];

    }
    foreach($s4 as  $keys => $v) {
        $value = explode(",",$v);
        foreach($value as $val) {
            if(strrchr($val,'-'))
            {
                $final[$keys][array_shift(explode("-",$val))] = end(explode("-",$val));
            }
            else
                $final[$keys][] = $val;
        }
    }

Upvotes: 0

Related Questions