如何使用GET方法从API获取数据并循环遍历它?

huangapple go评论52阅读模式
英文:

How to fetch data with get method from an api and loop throw it?

问题

I make a function and use http:get in order to fetch from an api, but as it is associative array it is hard to reach end of element such as title, how can solve it?

    
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Http;
use Illuminate\Http\Request;

class apiTest extends Controller
{
    function data()
    {
        $get = http::get('https://jsonplaceholder.typicode.com/posts');
        $data = $get->json();
        foreach ($data as $key => $datas) {
            foreach ($datas as $key => $value){
                echo $value;
            }
        }

    }

}
英文:

I make a function and use http:get in order to fetch from an api, but as it is associative array it is hard to reach end of element such as title, how can solve it?

<?php

namespace App\Http\Controllers;
use Illuminate\Support\Facades\Http;
use Illuminate\Http\Request;

    class apiTest extends Controller
    {
        function data()
        {
            $get = http::get('https://jsonplaceholder.typicode.com/posts');
             $data = $get ->json();
                foreach ($data as $key => $datas) {
                    foreach ($datas as $key => $value){
                        echo $value;
                    }
                }
    
        }
     
    }

答案1

得分: 1

请注意,在您的原始代码中,您对两个循环都使用了相同的变量名$key。为了避免冲突,请确保对每个循环使用唯一的变量名。

英文:
function data() {
    $get = http::get('https://jsonplaceholder.typicode.com/posts');
    $data = $get->json();
    
    foreach ($data as $item) {
        echo $item['title'];
    }
}

Note that in your original code, you used the same variable name $key for both loops. It's important to use unique variable names for each loop to avoid conflicts.

huangapple
  • 本文由 发表于 2023年6月25日 16:52:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76549622.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定