drw85135 2019-05-07 00:10
浏览 115
已采纳

如何解析存储在其中的字符串的php变量?

I'm new to php and am trying to parse a string I'm getting. The string is the result of a bash script I'm running, and I'm storing the output into a php variable. Here is the output I'm getting:

1/1 [==============================] - 1s 1s/step
[
  {
    "image_id": "mahomes1",
    "mean_score_prediction": 6.3682564571499825
  },
  {
    "image_id": "mahomes2",
    "mean_score_prediction": 6.7501190304756165
  },
  {
    "image_id": "mahomes3",
    "mean_score_prediction": 6.3136263862252235
  }, 
]

How would I go about parsing this string so that I can create a dictionary that stores the "image_id" value with the "mean_score_prediction" value?

  • 写回答

1条回答 默认 最新

  • dongxu6418 2019-05-07 00:22
    关注

    Your data is almost valid JSON, other than the beginning text and the comma between the final } and closing ]. By cleaning those issues up, you can then use json_decode on it to get a dictionary as an array of objects (or arrays, dependent on your preference):

    $string = preg_replace(array('/^[^\v]+/', '/,(\s+\])/'), array('', '$1'), $string);
    $dict = json_decode($string);
    print_r($dict);
    

    Output:

    Array ( 
      [0] => stdClass Object (
        [image_id] => mahomes1
        [mean_score_prediction] => 6.36825645715 
      )
      [1] => stdClass Object (
        [image_id] => mahomes2
        [mean_score_prediction] => 6.7501190304756
      )
      [2] => stdClass Object (
        [image_id] => mahomes3
        [mean_score_prediction] => 6.3136263862252
      ) 
    )
    

    To get an array of arrays, call json_decode with a second parameter of true i.e.

    $dict = json_decode($string, true);
    

    Demo on 3v4l.org

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作