英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论