首页 > 解决方案 > php 从多维数组中打印单个值

问题描述

我想从多维数组中打印一个值。

我正在调用https://www.myurl.com/ 以 Json 响应的 URL,例如:

{"data":{"country":"USA","currency":"USD","language":"American_English"}}

我的代码是:

<?php
$json = file_get_contents('https://www.myurl.com/');
$array = json_decode($json, TRUE);
print_r(array_values($array));
?>

结果是:

Array ( [0] => Array ( [country] => USA [currency] => USD [language] => American_English ) ) 

我的目标是只打印值“American_English”

我试过这个:

<?php
$json = file_get_contents('https://www.myurl.com/');
$array = json_decode($json, TRUE);
echo $array[0]["language"] ;
?>

我试过这个:

<?php
$json = file_get_contents('https://www.myurl.com/');
$array = json_decode($json, TRUE);
echo $array[0][2] ;
?>

我试过使用foreach

json = file_get_contents('https://myurl.com');
    $decode_data = json_decode($json);

foreach($decode_data as $key=>$value){
       echo $decode_data[0]['language']; //not working
       echo $decode_data[0][2]; //not working
       print_r($value); //same result od print_r above
}

然而,他们都没有达到我想要的。

标签: phparraysjsonmultidimensional-array

解决方案


就这么简单

$array = json_decode($json,true);
print_r($array);

echo $array['data']["language"] ;

结果

Array
(
    [data] => Array
        (
            [country] => USA
            [currency] => USD
            [language] => American_English
        )

)

American_English

推荐阅读