我有一个这样的字符串:
{ArrivalTime:300, ProductID:198, ArrivalDate:21/07/2017}, {ArrivalTime:582, ProductID:397, ArrivalDate:22/07/2017}
我使用了json_decode()但它没有工作;
我需要这样的返回数组:
Array
(
[0] => Array
(
[ArrivalTime] => 300
[ProductID] => 198
[ArrivalDate] => 21/07/2017
)
[1] => Array
(
[ArrivalTime] => 582
[ProductID] => 397
[ArrivalDate] => 21/07/2017
)
)
你帮我做那个吗?感谢。
答案 0 :(得分:1)
你可以尝试
str_split - 将字符串转换为数组
语法:
array str_split ( string $string [, int $split_length = 1 ] )
示例:
<?php
$str = "Hello Friend";
$arr1 = str_split($str);
print_r($arr1);
?>
编辑:
输出:
Array
(
[0] => H
[1] => e
[2] => l
[3] => l
[4] => o
[5] =>
[6] => F
[7] => r
[8] => i
[9] => e
[10] => n
[11] => d
)
替换您自己的字符串名称和数组名称。 谢谢。
答案 1 :(得分:1)
运行以下代码进行分析:
function strAnalyse($str){
preg_match_all('/(?<={)[^{}]*(?=})/',$str,$match);
$result = array();
foreach($match[0] as $item){
$one =array();
$tmp = explode(',',$item);
foreach($tmp as $kv){
$a = explode(':',$kv);
$one[trim($a[0])] = trim($a[1]);
}
array_push($result,$one);
}
echo '<pre>';
print_r($result);
}
结果:
Array
(
[0] => Array
(
[ArrivalTime] => 300
[ProductID] => 198
[ArrivalDate] => 21/07/2017
)
[1] => Array
(
[ArrivalTime] => 582
[ProductID] => 397
[ArrivalDate] => 22/07/2017
)
)
答案 2 :(得分:0)
你需要用[]和引号包装你的“json”字符串,当然(或检查,为什么它之前没有包装):
[{"ArrivalTime": 300,"ProductID": 198,"ArrivalDate": "21 / 07 / 2017"}, {"ArrivalTime": 582,"ProductID": 397,"ArrivalDate": "22 / 07 / 2017"}]
然后它将是正确的json格式和json_decode()创建正确的数组。
答案 3 :(得分:0)
即使我们添加“[]”(数组括号)
,json也无效string,number,object,array,true,false,null
在您的情况下,值字段中有一个日期通过括起“”(双引号)将其更改为字符串
“chars”
官方文档:http://www.json.org/
json的正确json格式是
[{
"ArrivalTime": 300,
"ProductID": 198,
"ArrivalDate": "21 / 07 / 2017"
}, {
"ArrivalTime": 582,
"ProductID": 397,
"ArrivalDate": "22 / 07 / 2017"
}]
答案 4 :(得分:0)
这不是有效的json格式。但如果你有这样的字符串,请尝试以下代码:
$string = "{ArrivalTime:300, ProductID:198, ArrivalDate:21/07/2017}, {ArrivalTime:582, ProductID:397, ArrivalDate:22/07/2017}";
$key = $value = $resultArray= array();
$arrayJson = explode('}, ', $string);
foreach ($arrayJson as $arrayJsonRep) {
$repJson = str_replace('{', '', $arrayJsonRep);
$repJson = str_replace('}', '', $repJson);
$repJsonExp = explode(', ', $repJson);
foreach ($repJsonExp as $x) {
$repJsonExpfirst= explode(':', $x);
array_push($key, $repJsonExpfirst[0]);
array_push($value, $repJsonExpfirst[1]);
}
$finalArray = array_combine($key, $value);
array_push($resultArray, $finalArray);
}
print_r($resultArray);