Skip to content
Advertisement

how can I add a list to existing json file?

I want to add a list to a json file if the list does not exist.

but when I try to use array() I’m getting 0 => 1=> 2=> instead of a list of objects

$list = array(
    "Version" => "1.0"
);

$users = array(
    "Users" => array(
    "Username"=> "test",
    "Level"=> "10"
    )
);

if(!isset($list['Users'])) {
    array_push($list, $users);
    echo json_encode($list);
}
exit;

result

{"Version":"1.0","0":{"Users":{"Username":"test","Level":"10"}}}

but my result should be

{"Version":"1.0","Users":[{"Username":"test","Level":"10"}]}

I’m new at php. regarding.

Advertisement

Answer

You can add the new key users if it doesn’t exist and then add elements to it, like this:

$list = array(
    "Version" => "1.0"
);

$users = array(
    "Users" => array(
    "Username"=> "test",
    "Level"=> "10"
    )
);

if(!isset($list['Users'])) $list['users']=[];

foreach( $users as $a ){
    $list['users'][]=$a;
}

echo json_encode( $list );

The output:

{"Version":"1.0","users":[{"Username":"test","Level":"10"}]}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement