php-字符串到键值(关联)数组类型的转换 [英] php - string to key-value (associative) array type conversion

查看:273
本文介绍了php-字符串到键值(关联)数组类型的转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have data as a string, for example:

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

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

How to convert it into "key=>value" (associative) array like this :

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

推荐答案

您可以使用

You can use json-decode and then cast to array:

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

或在json_decode中将assoc标志用作:

Or use the assoc flag in json_decode as:

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

这篇关于php-字符串到键值(关联)数组类型的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆