javascript - Json 的三维关联数组?

标签 javascript php arrays json

经过多次尝试,我不得不寻求一些帮助来解决这个问题。下面我有一些纯 JSON:

{
    "test": {
        "r1": [{
            "id": 1,
            "status": true
        }, {
            "id": 2,
            "status": true
        }],
        "r2": [{
            "id": 1,
            "status": false
        }, {
            "id": 2,
            "status": false
        }]
    }
}

当我从一个简单的 .txt 文件中读取时,这对 javascript 工作正常,但我想从 PHP 创建这个 JSON。我可以制作一个二维关联数组,但是为此我似乎需要一个三维关联数组,我无法解决!有人可以给我一个提示或替代解决方案吗?

最佳答案

这是一个关于如何将 JSON 对象(字符串)转换为 PHP 数组以及反之亦然的数据示例。
希望这能让您明白这一点。

<?php

// Original JSON object string
$jsonstring = '{
    "test":{
        "r1":[{
            "id":1,
            "status":true
        },{
            "id":2,
            "status":true
        }],
        "r2":[{
            "id":1,
            "status":false
        },{
            "id":2,
            "status":false
        }]
    }
}';

// Convert JSON string to PHP array
// This can be used by a PHP script to work on
$phparray = json_decode($jsonstring);
echo '<h3>PHP array converted from JSON string</h3><pre>'; var_dump($phparray); echo '</pre>';

// Convert it back to JSON string to prove it's the same
$jsonstring1 = json_encode($phparray);

// Now we create a PHP array corresponding to original JSON string, manually
$phparray = array (
    "test"=> array (
        "r1" => array(
            array(
                "id"=>1,
                "status"=>true
            ),
            array(
                "id"=>2,
                "status"=>true
            )
        ),
        "r2" => array(
            array(
                "id"=>1,
                "status"=>false
            ),
            array(
                "id"=>2,
                "status"=>false
            )
        )
    )
);

// Convert PHP array to JSON string
// This can be sent to a browser where it can be used by Javascript
$jsonstring2 = json_encode($phparray);

echo '<h3>Original JSON string</h3>' . $jsonstring;
echo '<h3>After conversion to array and back</h3>' . $jsonstring1;
echo '<h3>Converted from PHP array</h3>' . $jsonstring2;

?>

关于javascript - Json 的三维关联数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35241111/

相关文章:

javascript - HTML内容显示有限行

php - 使用 PHP 转换 SQL 时间?

javascript - 失败后如何退出测试循环

php - 询问有关使用 php 和远程数据库登录和注册的 android 教程

arrays - 用Z3记录

javascript - 如何将事件类添加到基于每个页面中的 URL 的导航菜单

php - 如何重置结果集以便再次循环它?

php - 从 mysql 检索数据返回相同的 3 行

arrays - 使用字符串标题将numpy数组保存到csv

javascript - 通过减少和数组返回对象数组