简体   繁体   中英

How can I define an array without a key within another array?

The title sounds a bit confusing, although I'm sure there's a simple solution. I'm using json_encode and am working on a web API. The web API will echo an array that is json_encoded. I want it to look like this:

{
    {
        "id": "test",
        "reason": "test reason"
    },
    {
        {
        "id": "test2",
        "reason": "test reason2"
    }
}

I've tried this:

$array = array();

$array[""] = array();
$array[""]["id"] = "test";
$array[""]["reason"] = "test reason";

$array[""] = array();
$array[""]["id"] = "test";
$array[""]["reason"] = "test reason";

This still has a key though ("") which is annoying. I don't want a key. How can I fix this? Thanks! :)

{
    {
        "id": "test",
        "reason": "test reason"
    },
    {
        {
        "id": "test2",
        "reason": "test reason2"
    }
}

This cannot be done for good reason : in javascript, the curly brackets indicate an object . Within an object, each property must have a key. The brackets on the other end indicate a numerically-indexed Array .

The Array type in php may be confusing because it's an all-in-one array, you can mix and match the keys as you see fit.

So this, instead, is valid JSON and might be what you really need (if you don't care about the keys, you'll need to loop over the values):

[
    {
        "id": "test",
        "reason": "test reason"
    },
    {
        {
        "id": "test2",
        "reason": "test reason2"
    }
]

EDIT

You may create such an array in php through json_encode() like this :

$array = [["id"=> "test","reason"=> "test reason"],["id"=> "test","reason"=> "test reason"]];
echo json_encode($array);

I think this is more in line with your original code, you nearly had it nailed

<?php
$array = array();

// create 1st detail entry
$arrayDetail = array();
$arrayDetail["id"] = "test";
$arrayDetail["reason"] = "test reason";

$array[] = $arrayDetail; // add detail to array

// create 2nd detail entry
$arrayDetail = array();
$arrayDetail["id"] = "test";
$arrayDetail["reason"] = "test reason";

$array[] = $arrayDetail; // add detail to array

// show the output
var_dump(json_encode($array, JSON_PRETTY_PRINT)); 

You may get such format as below with array_push method,

$array = array();
array_push($array, array('id' => 'test', 'reason' => 'test reason' ) );
echo json_encode($array);

The resut will be a valid json format as

[{"id":"test","reason":"test reason"}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM