0

我想将关联数组作为字符串存储到变量 a 中,然后将变量转换为数组。

$var='"electirc_bill"=>array(
                                   "type" => "number",
                                    "required"=>"yes"
                                  ),
      "electirc_bill_per"=>array(
                                   "type" => "number",
                                    "required"=>"yes"
                                 ),                   
              "gass_bill"=>array(     
                                   "type" => "number",
                                    "required"=>"yes"
                                  )
    )';

    var_dump($var);
4

5 回答 5

1

使用serializeunserialize

将数组转换为字符串:

$string = serialize($array);

将其转换回数组:

$array = unserialize($string);

编辑:根据您的评论,您似乎已经将数组存储为字符串并希望能够将其转换为数组。为此,我会使用eval它,但在将其与任何用户输入一起使用时要小心,因为它可能会导致代码中的安全漏洞。

我在这里使用您的代码做了一个小例子:http: //codepad.org/rPNXPBlW

$var = '$array_var = array("One" => array("1.1", "1.2"), "Two" => array("2.1", "‌​2.2"));';

eval($var);

echo $array_var['One'][0]; // Shows 1.1
于 2013-10-09T09:53:42.077 回答
0
  Here i give suggestion to use this array will meet your requirement 

$name=array('parent1'=>array('childone'=>'harish','childtwo'=>'vignesh'),'parent2'=>array('childone'=>'our children'));
echo "<pre>";
print_r($name);

foreach($name as $parents)
 {
  foreach($parents as $child)
   {
     echo "<pre>"; print_r($child);
   }
 }
于 2013-10-09T10:04:37.887 回答
0
// save
file_put_contents('file.json', json_encode($array));

// load
$array = json_decode(file_get_contents('file.json'), true);
于 2013-10-09T09:55:05.147 回答
0

您可以像这样使用序列化和反序列化:

<?
$var=array("electirc_bill"=>array(
                 "type" => "number",
                 "required"=>"yes"
               ),
      "electirc_bill_per"=>array(
                 "type" => "number",
                 "required"=>"yes"
               ),                   
      "gass_bill"=>array(     
               "type" => "number",
               "required"=>"yes"
           )
    );
    var_dump($var);
    $string = serialize($var);
    var_dump($string);
    $array = unserialize($string);
    var_dump($array );
?> 

工作代码

于 2013-10-09T10:01:49.227 回答
0

像下面这样使用,

$json_str = json_encode($var); 

first then use json_decode($json_str); where required 
于 2013-10-09T09:53:17.567 回答