【问题标题】:How to format the result of var dump (array)如何格式化 var dump (array) 的结果
【发布时间】:2021-12-25 03:30:12
【问题描述】:

我有这段代码,它从 API URL 获取一个数组。

                 <?php
                 $url = 'https://api.example.com/v1/w';
                 $data = file_get_contents($url);
                 $data = json_decode($data);
                 echo '<pre>' , var_dump($data->rule->deny_countries) , '</pre>';
                 ?>

显示如下:

       array(3) {
       [0]=>
       string(2) "US"
       [1]=>
       string(2) "ES"
       [2]=>
       string(2) "MX"
      }

我怎样才能只打印字符串的值? ( US、ES 和 MX )是国家/地区代码,我想将它们转换为完整的国家/地区名称,例如:美国、西班牙、墨西哥。

【问题讨论】:

    标签: php arrays json


    【解决方案1】:

    您可以使用此代码打印国家/地区代码:

    $country_code = $data->rule->deny_countries;
    echo $country_code[0]; // print US
    echo $country_code[1]; // print ES
    // ecc.
    

    您可以创建一个数组来将国家代码转换为国家名称,如下所示:

    $country_name = array("US"=>"United States", "ES"=>"Spain", "MX"=>"Mexico");
    

    然后您可以使用此代码打印国家/地区名称

    echo $country_name[$country_code[0]]; // print United States
    echo $country_name[$country_code[1]]; // print Spain
    // ecc.
    

    【讨论】:

    • 我真的很感谢你@Stefino76 它现在可以工作了panelcws.com/axel/decode.php 我可以在数组中的国家名称之前添加一个 img 吗?
    • 我想把国家的img国旗放在名字前,先谢谢了!
    • 您可以创建另一个数组,例如 $img_file = array("US"=>"us.png", "ES"=>"sp.png", "MX"=>"mx.png ");然后回显'
      '.$country_name[$country_code[1]].'
      ';
    • @AxelGomez - ...或者只是调用图像US.png 等等然后执行:src="' . $country_code[0] . '.png"
    • 谢谢!! @Stefino76 正在工作!你就是男人!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 2018-11-21
    • 1970-01-01
    • 1970-01-01
    • 2013-06-09
    相关资源
    最近更新 更多