这是我的php代码 [EDITED] :
$redis_data = file_get_contents("http://example.org/data/data.txt");
该代码返回以下json数据:
{"Phone":"08XXXXX","StartTime":"121212","Customer":"Customer A","time":1407921302}
{"Phone":"08XXXXX0","StartTime":"111111","Customer":"Customer B","time":1407921302
{"Phone":"08XXXXX","StartTime":"131313","Customer":"Customer C","time":1407921302}
这是我循环解析值的代码:
$redis_data = file_get_contents("http://example.org/data/data.txt");
$redis_data = json_decode($redis_data, true);
foreach ($redis_data as $data) {
echo $data['Phone'];
echo "<br>";
}
但我得到了这个错误:
Invalid argument supplied for foreach()
我做错了什么?
答案 0 :(得分:3)
您尝试获取的数据格式不正确json
[{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName": "Jones"}]
这是json语法。 并且您将获得以下格式的数据。
{"ANumber":"08122378673","BNumber":"500046","StartTime":"08122014102113","EndTime":"08122014104126","TrunkA":"S1JK2SBD1S","TrunkB":"N7JK2GSM1B","Customer":"PT.BNI","time":1407921302}
{"ANumber":"081351607600","BNumber":"14000","StartTime":"08122014102406","EndTime":"08122014103738","TrunkA":"S1JK2SSB1S","TrunkB":"EPJK2MNR0","Customer":"Bank Mandiri (CC_IB_Jasnita)","time":1407921302}
您可能需要重新格式化数据字符串
答案 1 :(得分:2)
你试图循环JSON - 而不是PHP。在尝试循环之前,您需要在json_decode
变量上运行$redis_data
(docs)。
$redis_data = json_decode($redis_data, true);
答案 2 :(得分:2)
你需要解码json才能循环播放它。
$redis_data = json_decode(file_get_contents("http://example.com/tes_files/data.txt"), true);
foreach ($redis_data as $data) {
echo $data['phone'];
}
答案 3 :(得分:1)
这是解决方案
$redis_data = explode( chr(10), file_get_contents("http://example.com/tes_redis/data.txt"));
foreach ($redis_data as $data) {
var_dump(json_decode($data));
$data = json_decode($data);
echo $data->Phone;
echo $data->StartTime;
echo $data->Customer;
//echo $data->ANumber;
//echo $data->BNumber;
}
您需要先导出数据。
答案 4 :(得分:0)
首先你必须使用 json_decode 函数将json转换为数组,它将给出数组,之后你可以循环
`
$jsonString =
'[{"Phone":"08XXXXX","StartTime":"121212","Customer":"Customer A","time":1407921302},
{"Phone":"08XXXXX0","StartTime":"111111","Customer":"Customer B","time":1407921302},
{"Phone":"08XXXXX","StartTime":"131313","Customer":"Customer C","time":1407921302} ]';
$array=json_decode($jsonString);
foreach ($arrayOfEmails as $data) {
echo $data->Phone."<br>";
}
`