yuda fajar
yuda fajar

Reputation: 25

how to make a nested array in php

I'm learning how to make nested arrays, following the json response that I made.

Upvotes: 0

Views: 91

Answers (3)

Melih Sevim
Melih Sevim

Reputation: 853

use db_paket_id in db_paket methods or

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

Upvotes: 0

Leandro Arruda
Leandro Arruda

Reputation: 506

There's array_merge function to combine arrays, then you can make an array of array:

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

And you must have an json as follow:

[
    { "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"
            }
        }
    }
]

Upvotes: 0

Giacomo M
Giacomo M

Reputation: 4711

You can use array_merge to merge two or more arrays.
In your case:

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

Upvotes: 1

Related Questions