简体   繁体   English

PHP-如何遍历此json响应?

[英]PHP - How can I iterate through this json response?

I have a json response from an API and I can't create an array from it with "json_decode" in PHP to iterate through this as an array. 我有一个来自API的json响应,因此无法在PHP中使用“ json_decode”从中创建一个数组来将其迭代为数组。 I always get "NULL", when I use "var_dump" to print out, what my "json_decode" returns. 我总是得到“ NULL”,当我使用“ var_dump”进行打印时,我的“ json_decode”返回什么。 The response-header of this API response is "application/json", but I am not familiar with this json format. 该API响应的响应标头为“ application / json”,但我对这种json格式不熟悉。

The json response from the API looks like this: 来自API的json响应如下所示:

[1,"Example name","307","7","Test","455",1458572100000]
[1,"Another example name","146","7","Test","455",1458571500000]
[1,"Test","304","7","Test","455",1458572280000]
[1,"Example name 3","163","7","Hello world","455",1458571080000]

This is the result/response of a single API request. 这是单个API请求的结果/响应。 Now, for example, I want to get the penultimate number (in this case everytime 455) of every line/object or, for example, the name (second value: "Example name", "Another example name", "Test" and so on). 现在,例如,我想获取每个行/对象的倒数第二个数字(在这种情况下,每次为455),或者例如,名称(第二个值:“示例名称”,“另一个示例名称”,“测试”和依此类推)。 How can I do this with php and this json format? 如何使用php和json格式执行此操作? It would be nice, if I can get an array from this to iterate through. 如果我可以从中获得一个数组进行迭代,那将是很好的。

It's a local realtime bus arrival API, but it's similar to/the same as content.tfl.gov.uk/… and I call this API with a simple http/get request using file_get_contents in PHP 这是一个本地实时公交到达API,但与content.tfl.gov.uk/…类似/相同,我使用PHP中的file_get_contents通过一个简单的http / get请求来调用此API

"/interfaces/ura/instant_V1?returnList=stopID,stopPointName,LineID,DestinationT‌​ext,estimatedTime,vehicleID&vehicleID=455")

To clarify, that's not JSON format that you're getting back. 要澄清的是,这不是您要返回的JSON格式。 But if that's what you're getting then you need a solution :) 但是,如果这就是您得到的,那么您需要一个解决方案:)

I would ignore the first & last character and use str_getcsv() to return the comma separated string as an array: 我会忽略第一个和最后一个字符,并使用str_getcsv()返回以逗号分隔的字符串作为数组:

$input = '[1,"Example name","307","7","Test","455",1458572100000]';
$array = str_getcsv(substr($input, 1, -1));

If you are having multple lines, then you'll want to split them into individual lines before doing the above with: 如果您有多行,那么在执行上述操作之前,您需要将它们分成几行:

$lines = explode($input, "]");
$array = array();
foreach($lines AS $line) {
    $input = '[1,"Example name","307","7","Test","455",1458572100000]';
    $array[] = str_getcsv(substr($input, 1, -1));
}

Updated to show delimeter of ] instead of \\n as per comment below. 更新为显示[ ]分隔符,而不是下面的注释所显示的\\n

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM