【问题标题】:php - string to key-value (associative) array type conversion [duplicate]php - 字符串到键值(关联)数组类型转换
【发布时间】:2019-04-30 00:17:47
【问题描述】:

我有数据作为字符串,例如:

$a = '{"ip":"111.11.1.1","country":"abc","country_code":"xy","city":"xxx"}';

如何将其转换为“key=>value”(关联)数组,如下所示:

   ip           => 111.11.1.1
   country      => abc
   country_code => xy
   city         => xxx

【问题讨论】:

    标签: php arrays string key-value


    【解决方案1】:

    你可以使用json-decode然后转换成array

    $str = '{"ip":"111.11.1.1","country":"abc","country_code":"xy","city":"xxx"}';
    $arr = (array)json_decode($str);
    

    或者使用 json_decode 中的assoc 标志为:

    $arr = json_decode($str, true);
    

    将导致:

    array(4) {
      'ip' =>
      string(10) "111.11.1.1"
      'country' =>
      string(3) "abc"
      'country_code' =>
      string(2) "xy"
      'city' =>
      string(3) "xxx"
    }
    

    【讨论】:

    • 非常感谢。这就是我要找的...
    • @KiranKumar 欢迎您 - 如果我的帖子对您​​有帮助,请将其标记为已接受
    • 是的,我接受了...
    【解决方案2】:

    您可以像这样简单地使用json_decode()

    $json = '{"ip":"111.11.1.1","country":"abc","country_code":"xy","city":"xxx"}';
    $arr = json_decode($json, true);
    print_r($arr);
    

    这将为您提供所需的结果。这将打印:

    Array ( [ip] => 111.11.1.1 [country] => abc [country_code] => xy [city] => xxx )
    

    【讨论】:

      猜你喜欢
      • 2016-07-21
      • 2012-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多