Convert string to associative array PHP [closed]

夙愿已清 提交于 2019-12-23 07:05:02

问题


I have a string:

string(133) "'status' => '-1','level1' => '1', 'level2' => '1', 'level9' => '1', 'level10' => '1', 'start' => '2013-12-13', 'stop' => '2013-12-13'"

How i do create an associative array? Result must be this:

array('status' => '-1', 'level1' => '1', ....);

Please help.


回答1:


Try this(with bad working variable names but its working ) -

<?php

$str = "'status' => '-1','level1' => '1', 'level2' => '1', 'level9' => '1', 'level10' => '1', 'start' => '2013-12-13', 'stop' => '2013-12-13'";

$mstr = explode(",",$str);
$a = array();
foreach($mstr as $nstr )
{
    $narr = explode("=>",$nstr);
$narr[0] = str_replace("\x98","",$narr[0]);
$ytr[1] = $narr[1];
$a[$narr[0]] = $ytr[1];
}
print_r($a);

Codepad Link - http://codepad.org/EqysY1CZ




回答2:


The fastest and the simple but REALLY INSECURE

$str = "array('3'=>'www.tension.com','1'=>'www.seomeuo.com','requestedBy'=>'1')";
eval("\$array = $str;");

You never should use this approach, there another ways to do it like: serialize() and unserialize()




回答3:


try this code and use explode() and foreach loop to get your output

<?php


   $string="'status' => '-1','level1' => '1', 'level2' => '1', 'level9' => '1', 'level10' => '1', 'start' => '2013-12-13', 'stop' => '2013-12-13'";

   $a=explode("=>",$string);
   $c=array();
   $i=0;
 foreach($a as $k=>$v){

   if($i%2==0){
   $b[]=$v;
   }else{
   $c[]=$v;
   }
   $i++;
   }
  $d=array_combine($b,$c);
 print_r($d);

?>



回答4:


I wanted to practice regex. One big problem is your string has both ',' and ', ' as delimiters so you need to fix that.

<?php
$var = "'status' => '-1','level1' => '1', 'level2' => '1', 'level9' => '1', 'level10' => '1', 'start' => '2013-12-13', 'stop' => '2013-12-13'";
$var = str_replace(', ', ',', $var);
$rows = explode(',', $var);
$array = [];
foreach($rows AS $row){
    preg_match("/^'(.+)' \=\> '(.+)'\$/", $row, $matches);
    $array[$matches[1]] = $matches[2];
}
var_dump($array);
?>

Example: http://ideone.com/4oad4t




回答5:


Dirty logic is here :)

<?php 
$str="'status' => '-1','level1' => '1', 'level2' => '1', 'level9' => '1', 'level10' => '1', 'start' => '2013-12-13', 'stop' => '2013-12-13'";
echo $str='$arr='.'array('.$str.');';
eval($str);
echo "<pre>";
print_r($arr);
?>



回答6:


You need to use the explode function in PHP.
refer-> http://cz1.php.net/explode



来源:https://stackoverflow.com/questions/20569829/convert-string-to-associative-array-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!