从外部API使用Laravel中的Guzzle获取实体中的所有数据

从外部API使用Laravel中的Guzzle获取实体中的所有数据,laravel,Laravel,我只想使用Laravel中的guzzle从外部API检索JSON响应中的电子邮件。这是我试过的 //Get all customer $allcus = 'https://api.paystack.co/customer'; $client = new Client(); $response = $client->request('GET', $allcus, [ 'headers' => [ 'Authorization' => 'Bearer '.'sk_li

我只想使用Laravel中的guzzle从外部API检索JSON响应中的电子邮件。这是我试过的

//Get all customer 
$allcus = 'https://api.paystack.co/customer';
$client = new Client();
$response = $client->request('GET', $allcus, [
  'headers' => [
    'Authorization' => 'Bearer '.'sk_live_#########################',
  ],
]); 

$cus_data = json_decode($response->getBody()->getContents()); 
//returns a json response of all customers
//dd($cus_data);

$cus_data_email = $cus_data->data->email;
dd($cus_data_email);
使用此选项将返回错误

$cus_data_email = $cus_data->data->email;
“消息”:“正在尝试获取非对象的属性‘email’”

但当我尝试此操作时,它返回第一个数组中的客户

$cus_data_email = $cus_data->data[0]->email;
我不想只回复一封客户电子邮件。我想检索所有客户的电子邮件


这就是JSON响应的方式

{
  "status": true,
  "message": "Customers retrieved",
  "data": [
    {
      "integration": ######,
      "first_name": null,
      "last_name": null,
      "email": "a###$gmail.com",
      "phone": null,
      "metadata": null,
      "domain": "live",
      "customer_code": "CUS_##########",
      "risk_action": "default",
      "id": #######,
      "createdAt": "2020-05-26T00:50:12.000Z",
      "updatedAt": "2020-05-26T00:50:12.000Z"
    },
    ...

你要找的是一个

$cus_data->data
是一个变量,可以同时存储多个值。这些可以通过索引访问,通常通过循环访问

我强烈建议阅读我提供的两个链接,我将使用的循环是一个
foreach
循环,因为它在这个上下文中是最可读的。所有的环都有它们的位置,所以熟悉它们是值得的

$emailsArray = []; // initialise an array
$emailsString = ""; // initialise a string

// Here's our loop, which will go over all the values of $cus_data->data
foreach($cus_data->data as $datum) {

    // $datum is the single value in $cus_data->data which we're currently looking at
    // Each of these values have an email property, which we access with arrow notation

    array_push($emailsArray, $datum->email); // add the email to our array
    $emailsString = $emailsString . $datum->email . ", "; // add the email to our string

}
接下来,
$emailsArray
将是一个数组(就像我们在上面学到的!),包含来自
$cus\u data->data
的所有电子邮件

$emailsString
将包含相同的信息,只包含在逗号分隔的字符串中

要注意的一件事是,如果你的一些数据没有电子邮件!那么上面的代码可能会失败

诚然,这不是最短的解决方案。对于这样的问题,我可能会使用。这里的代码以更详细的格式执行相同的操作,因此我们可以更好地理解它