chip
chip

Reputation: 3279

how to setup arrays to result to this json encoded format

how do I setup my arrays wherein when I call json_encode, it returns a result like this?

{
"rows":[
    {"id":1,"name":"Chai","price":18.00},
    {"id":2,"name":"Chang","price":19.00},
    {"id":3,"name":"Aniseed Syrup","price":10.00},
    {"id":4,"name":"Chef Anton's Cajun Seasoning","price":22.00},
    {"id":5,"name":"Chef Anton's Gumbo Mix","price":21.35},
    {"id":6,"name":"Grandma's Boysenberry Spread","price":25.00},
    {"id":7,"name":"Uncle Bob's Organic Dried Pears","price":30.00},
    {"id":8,"name":"Northwoods Cranberry Sauce","price":40.00},
    {"id":9,"name":"Mishi Kobe Niku","price":97.00}
],
"footer":[
    {"name":"Total","price":282.35}
]
}

I need to get 2 result sets, one for the actual rows and one for the sum of all the rows. I both convert them to arrays and combine them to be encoded to json, for consumption on the web page.

But in the end I would like to format them that way when I encode in json, it returns the format above. But when I try to join them, it appears the arrays get one dimension deeper. And this can't be read by easyUI.

Upvotes: 0

Views: 43

Answers (1)

petema3
petema3

Reputation: 121

json_encode([
    'rows' => [
        ["id" => 1, "name" => "Chai", "price" => 18.00],
        ["id" => 2, "name" => "Chang", "price" => 19.00],
        ["id" => 3, "name" => "Aniseed Syrup", "price" => 10.00],
        ["id" => 4, "name" => "Chef Anton's Cajun Seasoning", "price" => 22.00],
        ["id" => 5, "name" => "Chef Anton's Gumbo Mix", "price" => 21.35],
        ["id" => 6, "name" => "Grandma's Boysenberry Spread", "price" => 25.00],
        ["id" => 7, "name" => "Uncle Bob's Organic Dried Pears", "price" => 30.00],
        ["id" => 8, "name" => "Northwoods Cranberry Sauce", "price" => 40.00],
        ["id" => 9, "name" => "Mishi Kobe Niku", "price" => 97.00]
    ],
    'footer' => [
        [
            'name' => 'Total',
            'price' => 282.35
        ]
    ]
]);

This will give you the structure you're asking for, although it seems like the footer doesn't need to be an array like you have it in your question, which I assume is what you mean by it being one dimension deeper than necessary, in which case that part would instead be:

    'footer' => [
        'name' => 'Total',
        'price' => 282.35
    ]

Upvotes: 1

Related Questions