Imran Abbas
Imran Abbas

Reputation: 805

How to change json array format in php?

I have php script which is storing data into an array and then converting into json array. Following is script

$gameTraining = array();
$index = 0;
foreach($todayTraining->toArray() as $training){
    if($todayTraining[$index]['type'] === 'easy'){
        $gameTraining['easy'][]['game_id'] = $todayTraining[$index]['game_id'];
    }
    $index++;     
}
return $gameTraining;

And following response I am getting

{
    "training": {
        "easy": [
            {
                "game_id": 12
            },
            {
                "game_id": 6
            },
            {
                "game_id": 26
            }
        ]
    }
}

But I would like to remove the brackets from array, so can you kindly guide me how can I do that? I would like to convert as following

{
    "training": {
        "easy": [
                "game_id": 12,
                "game_id": 6,
                "game_id": 26
        ]
    }
}

Upvotes: 1

Views: 91

Answers (3)

Robiul Alam
Robiul Alam

Reputation: 11

Just use below line :

$gameTraining['easy'][] = $todayTraining[$index]['game_id'];

Instead of :

$gameTraining['easy'][]['game_id'] = $todayTraining[$index]['game_id'];

Hopefully, it will work.

Upvotes: 0

nakov
nakov

Reputation: 14268

You cannot have multiple items in an array with the same key. You can make an array with the ids for the game, so this line:

$gameTraining['easy'][]['game_id'] = $todayTraining[$index]['game_id'];

can be changed with this line:

$gameTraining['easy']['game_ids'][] = $todayTraining[$index]['game_id'];

Upvotes: 3

erickb
erickb

Reputation: 6309

Try something like this:

$todayTraining = [
    [
        'type' => 'easy',
        'game_id' => 123
    ],
    [
        'type' => 'easy',
        'game_id' => 456
    ]
];
$gameTraining = array();
$index = 0;
foreach($todayTraining as $training){
    if($todayTraining[$index]['type'] === 'easy'){
        $gameTraining['easy'][] = substr(json_encode(['game_id' => $todayTraining[$index]['game_id']]), 1, -1);
    }
    $index++;
}
echo json_encode($gameTraining, JSON_PRETTY_PRINT);

Upvotes: 0

Related Questions