无法通过foreach访问数组的一部分

时间:2018-07-31 18:03:08

标签: php laravel

我正在使用Botman创建用于电报的机器人,尝试从API响应获取值时遇到问题。

这是我的类,负责处理响应并将消息返回给用户,您可以看到API地址。

class TaxiService {

protected $client;
const TAXI_ENDPOINT = 'http://35.204.38.8:4000/api/v1/taxis/%s';

/**
 * DogService constructor
 *
 * @return void
 */
public function __construct(){
    $this->client = new Client();
}

public function hireTaxi(){
    try {
        $lon="Hello";
        $endpoint = sprintf(self::TAXI_ENDPOINT, 'Madrid');

        $response = json_decode(
            $this->client->get($endpoint)->getBody()
        );

        foreach($response as $key => $value){
            foreach($value as $key2 => $value2){
                if(is_array($value2)){
                    foreach($value2 as $key3 => $value3){
                        $lon = $value3;
                    }
                }
            }
        }

        return $lon;
    } catch (Exception $e) {
        // If anything goes wrong, we will be sending the user this error message.
        return 'An unexpected error occurred. Please try again later.';
    }
}

}

这是我在调用API时收到的响应。

[{"state":"free","name":"Opel","location": 
 {"lon":1.399,"lat":38.88},"city":"Madrid"}, 
 {"state":"free","name":"Skoda4","location": 
 {"lon":1.3123,"lat":38.123},"city":"Madrid"}, 
 {"state":"free","name":"Hyundai","location": 
 {"lon":1.2313,"lat":38.41},"city":"Madrid"}]

当我遍历“ json_decode”给定的数组时,“ $ long”变量返回“ Hello”,则在遍历数组时不设置任何值。

我要获取的是JSON位置中的值之一。

我已经在以下站点上测试了我的功能:http://sandbox.onlinephpfunctions.com/,它为我提供了属于JSON的值,这是我想要的,但似乎该功能在我的应用程序中无法正常工作。

3 个答案:

答案 0 :(得分:2)

您需要更改:

$response = json_decode(
    $this->client->get($endpoint)->getBody()
);

收件人:

$response = json_decode(
    $this->client->get($endpoint)->getBody(), true
);
  

为TRUE时,返回的对象将转换为关联数组。

答案 1 :(得分:0)

您将在每次迭代中覆盖$lon的值,这可能不是您想要的。如果您只想从返回的第一条记录中求出lon,则无需遍历所有内容,只需明确地获取第一条记录即可:

$response = json_decode(
    $this->client->get($endpoint)->getBody()
);
return $response[0]->location->lon;

甚至:

return json_decode($this->client->get($endpoint)->getBody())[0]->location->lon;

答案 2 :(得分:-1)

neoChiri,

看起来像范围问题。如果变量不存在,则会出现$long is not defined错误。因此,您稍后在代码中创建的某些变量将掩盖原始值。

希望这会有所帮助。