douchang6770 2016-09-08 14:51
浏览 35
已采纳

PHP - 从API给出的字符串创建数组

I have a string containing that is being returned from an API which is dynamic, an example of the string is below:

[[[1473261033000,3.7933],[1473312464000,2.0295],[1473313206000,2.0844],[1473313505000,1.4888],[1473313805000,1.3003],[1473314105000,1.1164]]]

I cant really do anything with it like this so i would like to split it into 2 arrays, one for the first number and one for the second, like so:

Array1

  • 1473261033000
  • 1473312464000
  • 1473313206000
  • 1473313505000
  • 1473313805000
  • 1473314105000

Array2

  • 3.7933
  • 2.0295
  • 2.0844
  • 1.4888
  • 1.3003
  • 1.1164

Would someone help me out on how i could go about this? its driving me nuts.

  • 写回答

2条回答 默认 最新

  • dongnaigu2052 2016-09-08 14:55
    关注

    You need to first decode the JSON string into an array, then use array_column to extract the two arrays.

    This will require PHP >=5.5, but if you require a lower version then you should be able to find a backwards compatible version of the function on the documentation page.

    <?php
    $str = '[[[1473261033000,3.7933],[1473312464000,2.0295],[1473313206000,2.0844],[1473313505000,1.4888],[1473313805000,1.3003],[1473314105000,1.1164]]]';
    $json = json_decode($str, true)[0];
    
    $first = array_column($json, 0);
    $second = array_column($json, 1);
    
    print_r($first);
    print_r($second);
    

    See https://eval.in/637961 for a demo.

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

报告相同问题?

悬赏问题

  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊