我有一个像以下一样的字符串...
Array ([product_name] => this is a product [product_desc] => some descripyion [cat_id] => 3)
这看起来像一个数组,但这是一个字符串。如果我使用echo,那么它会打印相同的结果。
$someVariable = "Array ([product_name] => this is a product [product_desc] => some descripyion [cat_id] => 3)";
echo $someVariable;
结果:
Array ([product_name] => this is a product [product_desc] => some descripyion [cat_id] => 3)
我需要它转换为数组,以便我可以执行以下操作..
echo $someVariable['product_name'];
并获得以下结果
this is a product
有没有办法做到这一点?
由于
答案 0 :(得分:5)
serialize
数据:
<input type="hidden" name="data" valaue='<?php print_r(serialize($yourData));?>'>
然后unserialize
:
<?php
$youralldata = unserialize($_POST['data']);
print_r($youralldata);
?>
答案 1 :(得分:2)
$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]);
这会将字符串转换回数组。
答案 2 :(得分:0)
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'];