【问题标题】:Get all Data in a Body using Guzzle in Laravel from External API使用 Laravel 中的 Guzzle 从外部 API 获取正文中的所有数据
【发布时间】:2020-05-28 05:48:53
【问题描述】:

我只想使用 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;

"message": "尝试获取非对象的属性 '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"
    },
    ...

【问题讨论】:

    标签: laravel


    【解决方案1】:

    你要找的是loop

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

    我强烈建议阅读我提供的两个链接,我将使用的循环是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_data->data 的所有电子邮件。

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

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

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

    【讨论】:

      猜你喜欢
      • 2015-12-04
      • 1970-01-01
      • 2020-01-10
      • 1970-01-01
      • 2017-12-06
      • 2020-09-16
      • 2021-04-25
      • 2018-03-08
      • 2017-07-06
      相关资源
      最近更新 更多