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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?