在我的服务器端,我收到以下格式的请求:
"medium x 1, small x 2"
如何以这种格式转换这些数据:
array(0:{"medium"=>1},1:{"small"=>2})
谢谢!
答案 0 :(得分:3)
这很简单,利用explode()
并使用foreach() {...}
循环:
$str = "medium x 1, small x 2";
$a = explode(",", $str);
$data = array();
foreach($a as $s) {
list($size, $quantity) = explode('x', $s);
$data[] = array($size => $quantity);
}
// show it
print(json_encode($data));
返回:
[{"medium ":" 1"},{" small ":" 2"}]