doufan6886 2013-05-17 22:13
浏览 34
已采纳

PHP preg_split和替换

I currently have this code running. It is splitting the variable $json where there are },{ but it also removes these characters, but really I need the trailing and leading brackets for the json_decode function to work. I have created a work around, but was wondering if there is a more elegant solution?

<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5},{"a":1,"b":2,"c":3,"d":4,"e":5}';
$individuals = preg_split('/},{/',$json);

$loop_count =1;
foreach($individuals as $object){
    if($loop_count == 1){$object .='}';}
    else{$object ="{".$object;}
    print_r(json_decode($object));
    echo '<br />';
$loop_count++;
}
?>

EDIT: The $json variable is actually retrieved as a json object. An proper example would be

[{"id":"foo","row":1,"col":1,"height":4,"width":5},{"id":"bar","row":2,"col":3,"height":4,"width":5}]

  • 写回答

2条回答 默认 最新

  • dounanyin3179 2013-05-17 22:17
    关注

    As you (presumably) already know, the string you have to start with isn't valid json because of the comma and the two objects; it's basically two json strings with a comma between them.

    You're trying to solve this by splitting them, but there's a much easier way to fix this:

    The work-around is simply to turn the string into valid JSON by wrapping it in square brackets:

    $json = '[' . $json . ']';
    

    Voila. The string is now valid json, and will be parsed successfully with a single call to json_decode().

    Hope that helps.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?