我怎样才能让我的foreach循环一次返回routeTitle和相关的分钟,而不是先将标题和后面的分钟都给出?
我的代码:
<?php
// parameters
$hubVerifyToken = '#######';
$accessToken = "########";
// check token at setup
if ($_REQUEST['hub_verify_token'] === $hubVerifyToken) {
echo $_REQUEST['hub_challenge'];
exit;
}
// handle bot's anwser
$input = json_decode(file_get_contents('php://input'), true);
$senderId = $input['entry'][0]['messaging'][0]['sender']['id'];
$messageText = $input['entry'][0]['messaging'][0]['message']['text'];
**$stopid = $messageText;
$urlbase = "http://webservices.nextbus.com/service/publicXMLFeed?command=predictions&a=ttc&stopId=";
$url = $urlbase.$stopid;
$xml = simplexml_load_file($url);
$rt = $xml->predictions;
foreach ($rt as $value) {
$messagetitles .= $value->attributes()->routeTitle." arriving in ";
if(isset($value->direction)){
foreach($value->direction->prediction as $attr){
foreach($attr->attributes() as $k => $v){
if($k == 'minutes'){
$messageminutes .= $v." min |";
}
}
}
}else{
$messageminutes = "Error this bus isn't running";
}
}
if($messageText == "hi") {
$answer = "Type your Stop ID for the latest times.";
}
$response = [
'recipient' => [ 'id' => $senderId ],
'message' => [ 'text' => $messagetitles.$messageminutes]
];**
$ch = curl_init('https://graph.facebook.com/v2.6/me/messages?access_token='.$accessToken);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($response));
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_exec($ch);
curl_close($ch);
我尝试过:连接字符串
foreach ($rt as $value) {
$messagetitles .= $value->attributes()->routeTitle." arriving in ";
if(isset($value->direction)){
foreach($value->direction->prediction as $attr){
foreach($attr->attributes() as $k => $v){
if($k == 'minutes'){
$messageminutes .= $v." min |";
}
}
}
}else{
$messageminutes = "Error this bus isn't running";
}
}
但是这首先返回所有的routeTitles,然后单独返回时间,如下所示:
325-Don Mills抵达185-Don Mills Rocket抵达25-Don Mills抵达错误此公共汽车未运行15分钟| 39分钟| 43分钟| 46分钟|
我也尝试将$ messagetitles变量添加到$ messageminutes中,如下所示:
if($k == 'minutes'){
$messageminutes .= $messagetitles.$v." min |";
}
但这只有在通过该巴士站只有1条路线时才有效。
我如何每次在循环中返回routeTitle及其每个分钟属性?
XML Feed示例:XMLfeed
答案 0 :(得分:0)
在一些帮助下,我能够认识到连接字符串是可行的方法,但我的变量需要重新安排。请参阅下面的正确顺序输出成功:
foreach ($rt as $value) {
$messagetitles = $value->attributes()->routeTitle ;
$messageminutes = "" ;
$final .= $messagetitles ;
if(isset($value->direction)){
$final .=" arriving in ";
foreach($value->direction->prediction as $attr){
foreach($attr->attributes() as $k => $v){
if($k == 'minutes'){
$messageminutes .= " ".$v." min,";
}
}
}
}else{
$messageminutes = " is currently not available.";
}
$final .= $messageminutes ;
$final .= " | " ;
}