首页 > 解决方案 > 如何从下面给出的 json 中显示 tld 值

问题描述

从下面的 json 我需要显示 tld 的值,即 co.uk、eu、live、org...

Array ( [tldlist] => Array ( [tld] => Array ( [0] => Array ( [tld] => co.uk ) [1] => Array ( [tld] => eu ) [2] => Array ( [tld] => live ) [3] => Array ( [tld] => org ) [4] => Array ( [tld] => Array ( ) ) ) [tldcount] => 5 ) [Command] => GETTLDLIST [APIType] => API [Language] => eng [ErrCount] => 0 [ResponseCount] => 0 [MinPeriod] => Array ( ) [MaxPeriod] => 10 [Server] => SJL1VWRESELL_T [Site] => eNom [IsLockable] => Array ( ) [IsRealTimeTLD] => Array ( ) [TimeDifference] => +0.00 [ExecTime] => 0.000 [Done] => true [TrackingKey] => 7cbc3d47-c11c-4a39-8387-448777e82af5 [RequestDateTime] => 5/14/2018 12:21:18 AM [debug] => Array ( ) ) 1

在我的刀片代码下面找到:

 @foreach($final_data1['tldlist']['tld'] as $key)

    {{$key}}<br>

 @endforeach

请建议我在我的刀片文件中进行更正以显示上述 json 中的 tld。

标签: phplaravel

解决方案


初步说明:您显示的“json”不是 JSON,它是print_r().


由于 JSON 只是一个字符串,因此您需要先对其进行解码。PHP 文档指出:

功能

json_decode ( 字符串 $json [, bool $assoc = FALSE [, int $depth = 512 [, int $options = 0 ]]] )

参数

$json 被解码的 json 字符串。

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

所以关联数组在解码后可以作为对象访问:

$data = json_decode($json);
$tld = $data->tldlist;

如果您希望将其解码为数组true,请作为第二个参数传递:

$data = json_decode($json, true);
$tld = $data['tldlist'];

我建议在控制器中对其进行解码。这样你的视图就不需要关心数据是如何传递的。

假设您有一个 JSON 字符串并希望将其作为数组访问:

return view('your_blade_view')->with('final_data1', json_decode($data, true));

如果您坚持在 Blade 文件中执行此操作,请使用以下代码段:

@foreach($final_data1['tldlist']['tld'] as $key)

    {{$key}}<br>

@endforeach

推荐阅读