如何将json对象转换为key->值数组

时间:2015-12-10 12:56:30

标签: php arrays json

我有一个看起来像这样的json对象(为了便于阅读而被截断):

{"value":["Afghanistan","Albania","Algeria","American Samoa","Andorra","Angola","Anguilla","Antarctica","Antigua and Barbuda"
],"order":[0,1,2,3,4,5,6,7,8,9
]}

我如何使用PHP创建一个key-gt;值数组,我可以在select循环中使用它?

我知道如何从PHP数组中进行选择,但是这个JSON的奇怪设置让我难以理解。我需要使用JSON对象的“value”部分作为值,使用“order”作为键。

任何指针或想法都将不胜感激。

3 个答案:

答案 0 :(得分:3)

你可以使用json_decode:

$arr = json_decode($json, true);

假设$ json是你的字符串

答案 1 :(得分:2)

这应该可以帮到你

// your JSON string
$json = '{"value":["Afghanistan","Albania","Algeria","American Samoa","Andorra","Angola","Anguilla","Antarctica","Antigua and Barbuda"],"order":[0,1,2,3,4,5,6,7,8,9]}';

// decode the JSON string into a usable data structure in PHP
$data = json_decode($json);

// create an empty array to store your result
$map = array();

// iterate over the $data
// map each `order` to each `value`
foreach ($data->order as $idx => $key) {
  $map[$key] = $data->value[$idx];
}

// display the result
var_dump($map);

输出

array(10) {
  [0]=>
  string(11) "Afghanistan"
  [1]=>
  string(7) "Albania"
  [2]=>
  string(7) "Algeria"
  [3]=>
  string(14) "American Samoa"
  [4]=>
  string(7) "Andorra"
  [5]=>
  string(6) "Angola"
  [6]=>
  string(8) "Anguilla"
  [7]=>
  string(10) "Antarctica"
  [8]=>
  string(19) "Antigua and Barbuda"
  [9]=>
  NULL
}

您会注意到key:9(第10个密钥)为NULL,因为您只有 9 值。

答案 2 :(得分:0)

试试这个:

$json = '{"value":["Afghanistan","Albania","Algeria","American Samoa","Andorra","Angola","Anguilla","Antarctica","Antigua", "Barbuda"],"order":[0,1,2,3,4,5,6,7,8,9]}';
// create a temp array to access the JSON-Data
$array = json_decode($json, true);
// Combine the two "parts" of the JSON-Data as keys and values of the new array
$array = array_combine($array['order'], $array['value']);

print_r($array);

输出将是:

Array
(
    [0] => Afghanistan
    [1] => Albania
    [2] => Algeria
    [3] => American Samoa
    [4] => Andorra
    [5] => Angola
    [6] => Anguilla
    [7] => Antarctica
    [8] => Antigua
    [9] => Barbuda
)

(!)我的解决方案需要相同数量的Kys和值。你的JSON是"错误"为我的解决方案。我纠正了这个问题("安提瓜和巴布达" - >"安提瓜","巴布达") 看看@naomik帖子