如何在php中创建嵌套数组

时间:2019-12-19 12:37:47

标签: php arrays json codeigniter object

我正在按照我做出的json响应学习如何制作嵌套数组。

3 个答案:

答案 0 :(得分:1)

您可以使用array_merge合并两个或多个数组。
就您而言:

$res = [
    'data' => array_merge(
        $this->M_wilayah->db_paket($origin,$destinasi),
        ['harga' => $this->M_wilayah->db_paket_id($origin,$destinasi)]
    )
];

答案 1 :(得分:0)

array_merge function可以组合数组,那么您可以创建一个数组数组:

$res = [
    'data' => array_merge(
        $this->M_wilayah->db_paket($origin, $destinasi),
        ['harga' => $this->M_wilayah->db_paket_id($origin, $destinasi)]
 )
];

并且您必须具有以下json:

[
    { "data": {
            "id_origin": "1",
            "origin": "jakarta raya",
            "id_destinasi": "7",
            "destinasi": "DKI Jakarta, Kota Jakarta Pusat, Tanah Abang, Bendungan Hilir, 10210",
            "harga": {
                "reguler": "8500",
                "nextday": "15000"
            }
        }    
    },
    { "data": {
            "id_origin": "2",
            "origin": "another origin",
            "id_destinasi": "8",
            "destinasi": " another data like DKI Jakarta, Kota Jakarta Pusat, Tanah Abang, Bendungan Hilir, 10210",
            "harga": {
                "reguler": "8500",
                "nextday": "15000"
            }
        }
    }
]

答案 2 :(得分:0)

在db_paket方法中使用db_paket_id 或

$res['data']['harga'] = $this->M_wilayah->db_paket_id($origin, $destinasi);