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 浏览文件夹的图库,视频,图片之类的怎样删除?
  • ¥15 怎么把512还原为520格式
  • ¥15 MATLAB的动态模态分解出现错误,以CFX非定常模拟结果为快照
  • ¥15 求高通平台Softsim调试经验
  • ¥15 canal如何实现将mysql多张表(月表)采集入库到目标表中(一张表)?
  • ¥15 wpf ScrollViewer实现冻结左侧宽度w范围内的视图
  • ¥15 栅极驱动低侧烧毁MOSFET
  • ¥30 写segy数据时出错3
  • ¥100 linux下qt运行QCefView demo报错
  • ¥50 F1C100S下的红外解码IR_RX驱动问题