多维数组 PHP-JSON
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19454208/
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
Multidimensional array PHP-JSON
提问by user2886519
How to create an array in PHP that with json_encode() becomes a thing with following structure:
如何在 PHP 中使用 json_encode() 创建一个数组,该数组具有以下结构:
Array(
[1] => Array(
[id] => 1
[data] => 45
)
[2] => Array(
[id] => 3
[data] => 54
)
);
回答by Charles R
Try something like this:
尝试这样的事情:
//initialize array
$myArray = array();
//set up the nested associative arrays using literal array notation
$firstArray = array("id" => 1, "data" => 45);
$secondArray = array("id" => 3, "data" => 54);
//push items onto main array with bracket notation (this will result in numbered indexes)
$myArray[] = $firstArray;
$myArray[] = $secondArray;
//convert to json
$json = json_encode($myArray);
回答by ewwink
Here is a shorter way:
这是一个更短的方法:
$myArray = array();
$myArray[] = array("id" => 1, "data" => 45);
$myArray[] = array("id" => 3, "data" => 54);
//convert to json
$json = json_encode($myArray);
回答by Swatantra Kumar
This example PHP array is mixed, with the outer level numerically indexed and the second level associative:
这个示例 PHP 数组是混合的,外层是数字索引,第二层是关联的:
<?php
// PHP array
$books = array(
array(
"title" => "Professional JavaScript",
"author" => "Nicholas C. Zakas"
),
array(
"title" => "JavaScript: The Definitive Guide",
"author" => "David Flanagan"
),
array(
"title" => "High Performance JavaScript",
"author" => "Nicholas C. Zakas"
)
);
?>
In the json_encodeoutput, the outer level is an array literal while the second level forms object literals. This example demonstrates using the JSON_PRETTY_PRINT option with json_encode for more readable output as shown in code comments below:
在json_encode输出中,外层是数组字面量,而第二层是对象字面量。此示例演示将 JSON_PRETTY_PRINT 选项与 json_encode 一起使用以获得更易读的输出,如下面的代码注释所示:
<script type="text/javascript">
// pass PHP array to JavaScript
var books = <?php echo json_encode($books, JSON_PRETTY_PRINT) ?>;
// output using JSON_PRETTY_PRINT
/* var books = [ // outer level array literal
{ // second level object literals
"title": "Professional JavaScript",
"author": "Nicholas C. Zakas"
},
{
"title": "JavaScript: The Definitive Guide",
"author": "David Flanagan"
},
{
"title": "High Performance JavaScript",
"author": "Nicholas C. Zakas"
}
]; */
// how to access
console.log( books[1].author ); // David Flanagan
</script>