1

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
        ]
    }
}
2
  • Your output is not a Valid JSON Commented Aug 8, 2019 at 5:53
  • Your using foreach() to give you the element in $training, but then you are getting values from $todayTraining[$index] where you are maintaining $index yourself. Commented Aug 8, 2019 at 6:02

3 Answers 3

3

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'];
Sign up to request clarification or add additional context in comments.

1 Comment

@RakeshJakhar, the key was set to game_ids on purpose, because it will contain multiple ids, not just one.
0

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);

Comments

0

Just use below line :

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

Instead of :

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

Hopefully, it will work.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.