8

如何在 PHP 中使用 json_encode() 创建一个数组,该数组具有以下结构:

Array(
[1] => Array(
    [id] => 1
    [data] => 45
)
[2] => Array(
    [id] => 3
    [data] => 54
)
);
4

3 回答 3

16

尝试这样的事情:

//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);
于 2013-10-18T16:18:47.857 回答
7

这是一个更短的方法:

$myArray = array();

$myArray[] = array("id" => 1, "data" => 45);
$myArray[] = array("id" => 3, "data" => 54);

//convert to json
$json = json_encode($myArray);
于 2014-01-21T10:30:32.680 回答
2

这个示例 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"
    )
);
?>

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>
于 2015-10-18T08:18:19.663 回答