【问题标题】:php print a single value from a multidimensional arrayphp 从多维数组中打印单个值
【发布时间】:2021-07-19 09:17:57
【问题描述】:

我想打印多维数组中的单个值。

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

{"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
}

但是他们都没有达到我想要的。

【问题讨论】:

    标签: php arrays json multidimensional-array


    【解决方案1】:

    简单点

    $array = json_decode($json,true);
    print_r($array);
    
    echo $array['data']["language"] ;
    

    结果

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

    【讨论】:

      【解决方案2】:
      <?php
      $json = file_get_contents('https://www.myurl.com/');
      $array = json_decode($json, true);
      print_r($array['data']['language']);
      ?>
      
      

      你可以使用这个 sn-p 来可视化数组

      <?php
      echo '<pre>';
      print_r($array); // or var_dump($array);
      echo '</pre>';
      ?>
      

      【讨论】:

        猜你喜欢
        • 2020-04-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多