Tanvir
Tanvir

Reputation: 1695

string to array conversion using php

I have a string like following...

Array ([product_name] => this is a product [product_desc] => some descripyion [cat_id] => 3)

This is looking like as an array but this is a string. If I use echo then it prints the same result.

$someVariable = "Array ([product_name] => this is a product [product_desc] => some descripyion [cat_id] => 3)";

echo $someVariable;

Result:

Array ([product_name] => this is a product [product_desc] => some descripyion [cat_id] => 3)

I need it to convert to an array so that I can do the following..

echo $someVariable['product_name'];

and get the following result

this is a product

Is there any way to do this ?

Thanks

Upvotes: 3

Views: 118

Answers (3)

Bipul Khan
Bipul Khan

Reputation: 707

serialize the data:

<input type="hidden" name="data" valaue='<?php print_r(serialize($yourData));?>'>

And then unserialize:

<?php 
    $youralldata = unserialize($_POST['data']);
    print_r($youralldata);
?>

Upvotes: 5

Dastagir
Dastagir

Reputation: 1012

 function stringToArray($string){
    $pattern = '/\[(.*?)\]|=>\s+[\w\s\d]+/';
    preg_match_all($pattern,$string,$matches);
    $result = array();
    foreach($matches[0] as $i => $match){
        if($i%2 == 0){
                    $key = trim(str_ireplace(array("[","]"),"",$match));
            $value = trim(str_ireplace(array("=>"),"",$matches[0][$i+1]));
            $result[$key] = $value;
        }
    }
    return $result;
}

$someVariable =   "Array ([product_name] => this is a product [product_desc] => some descripyion [cat_id] => 3)";

$someVariable = stringToArray($someVariable);

echo $someVariable['product_name'];

Upvotes: 0

Teaqu
Teaqu

Reputation: 3263

$someVariable = "Array ([product_name] => this is a product [product_desc] => some descripyion [cat_id] => 3)";

preg_match_all('/\[(.*?)\]/', $someVariable, $keys);
preg_match_all('/=> (.*?) ?[\[|\)]/', $someVariable, $values);

$someVariable = array_combine($keys[1], $values[1]);

This converts the string back into an array.

Upvotes: 2

Related Questions