[{dmID=2311,attentionDate=1317368188.262348,attentionDegree=272,attentionCount=16},{dmID=2312,attentionDate=1317368197.902157,attentionDegree=72,attentionCount=8},{dmID=2313,attentionDate=1317368223.751104,attentionDegree=42,attentionCount=6}]能不能将上面的字符串转为数组, dmID,attentionDate attentionDegree attentionCount为key谢谢
$str = <<<TXT
[{dmID=2311,attentionDate=1317368188.262348,attentionDegree=272,attentionCount=16},
{dmID=2312,attentionDate=1317368197.902157,attentionDegree=72,attentionCount=8},
{dmID=2313,attentionDate=1317368223.751104,attentionDegree=42,attentionCount=6}]
TXT;
$str = preg_replace(array('/(\w+)=/', '/=([^,}]+)/'), array('"$1":', '"$1"'), $str);
echo '<pre>';var_dump(json_decode($str));
/**
输出结果:
array
0 =>
object(stdClass)[1]
public 'dmID' => int 2311
public 'attentionDate' => float 1317368188.2623
public 'attentionDegree' => int 272
public 'attentionCount' => int 16
1 =>
object(stdClass)[2]
public 'dmID' => int 2312
public 'attentionDate' => float 1317368197.9022
public 'attentionDegree' => int 72
public 'attentionCount' => int 8
2 =>
object(stdClass)[3]
public 'dmID' => int 2313
public 'attentionDate' => float 1317368223.7511
public 'attentionDegree' => int 42
public 'attentionCount' => int 6
*/
//多加一步,转为array
$str = <<<TXT
[{dmID=2311,attentionDate=1317368188.262348,attentionDegree=272,attentionCount=16},
{dmID=2312,attentionDate=1317368197.902157,attentionDegree=72,attentionCount=8},
{dmID=2313,attentionDate=1317368223.751104,attentionDegree=42,attentionCount=6}]
TXT;
$str = preg_replace(array('/(\w+)=/', '/=([^,}]+)/'), array('"$1":', '"$1"'), $str);
$json = json_decode($str);
foreach($json as $k=>$j) {
$json[$k] = (array)$j;
}
echo '<pre>';var_dump($json);
/**
输出结果:
array
0 =>
array
'dmID' => int 2311
'attentionDate' => float 1317368188.2623
'attentionDegree' => int 272
'attentionCount' => int 16
1 =>
array
'dmID' => int 2312
'attentionDate' => float 1317368197.9022
'attentionDegree' => int 72
'attentionCount' => int 8
2 =>
array
'dmID' => int 2313
'attentionDate' => float 1317368223.7511
'attentionDegree' => int 42
'attentionCount' => int 6
*/
json_decode($str, true) 就是数组了