将 php 数组转换为单个 JSON 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18432914/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
convert php array into single JSON object
提问by chowwy
I converted a PHP array into JSON, using json_encode. I checked the console, and the objects are displaying in array, but as individual objects.
我使用 json_encode 将 PHP 数组转换为 JSON。我检查了控制台,对象显示在数组中,但作为单独的对象。
[ { Object { 03-13-2012="Jazz"}, Object { 07-19-2012="Pop"}, ... ]
How can I convert this array into one object, like this (in PHP or jQuery):
如何将此数组转换为一个对象,如下所示(在 PHP 或 jQuery 中):
Object { 03-13-2012="Jazz", 07-19-2012="Pop"}
Edit: Here's the beginning of my print_r for the PHP array:
编辑:这是 PHP 数组的 print_r 的开头:
Array
(
[0] => Array
(
[03-13-2012] => Jazz
)
[1] => Array
(
[07-19-2012] => Pop
)
)
回答by Baba
Don't be afraid of loops
不要害怕循环
$output = array();
foreach($data as $v) {
$output[key($v)] = current($v);
}
echo json_encode($output, 128);
回答by SteAp
In general, you need to prepare such a PHP array, which then should be json_encodeand passed along to the server:
一般来说,你需要准备这样一个 PHP 数组,然后它应该是json_encode并传递给服务器:
$data = array(
'03-13-2012' => 'Jazz',
'07-19-2012' => 'Pop',
);
echo json_encode( $data );
exit;
回答by manchicken
You'll want to iterate over the indexed array making the keys of an associative array found therein into keys in a second associative array.
您需要遍历索引数组,将其中找到的关联数组的键转换为第二个关联数组中的键。
Assumption: You're starting with a JSON string, and you want to end up with a JSON string.
假设:您从一个 JSON 字符串开始,并希望以一个 JSON 字符串结束。
Warning: If you encounter duplicates you will overwrite.
警告:如果您遇到重复项,您将被覆盖。
Here's an example of what I'm talking about:
这是我正在谈论的一个例子:
<?php
$foo = json_decode('[{"abc":"A123"},{"xyz":"B234"}]');
$bar = array();
foreach ($foo as $f) {
foreach ($f as $k => $v) {
$bar[$k] = $v;
}
}
echo json_encode($foo)."\n";
echo json_encode($bar)."\n";
?>