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 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 关于#python#的问题:自动化测试