I have this PHP code:

$goodname = 'name'; $goodlvl = '6'; $name = "goods.json"; $arr = array( 'name' => $goodname, 'lvl' => $goodlvl ); file_put_contents($name, json_encode($arr, JSON_UNESCAPED_UNICODE)); 

It creates a PHP array, converts it to JSON format, and shoves goods.json

It seems everything works, but not as I need. This is what this script does with the goods.json file:

 {"name":"123","lvl":"6"} 

It carries the elements of the array. I want to know how to make the PHP script give this array a name to make something like this

 { "account" : { "name: "123", "lvl" : "6" } } 

All in order to be able to create these accounts and specify (drive in the inputs) statistics: name and level, and the PHP script created them and entered them in goods.json

2 answers 2

Give the array a name, and it will fit in json $ goodname = 'name'; $ goodlvl = '6';

 $name = "goods.json"; $arr = array( "player" => array ( 'name' => $goodname, 'lvl' => $goodlvl ) ); echo json_encode($arr, JSON_UNESCAPED_UNICODE); 

Displays: {"player":{"name":"name","lvl":"6"}}

  • one
    Plus JSON_PRETTY_PRINT - u_mulder
  • Thank you all very much) - newArray

To get from your code such json tex:

{ "account" : { "name: "123", "lvl" : "6" } }

Your code should look like this:

 $goodname = '123'; $goodlvl = '6'; $name = "goods.json"; $arr = array( 'name' => $goodname, 'lvl' => $goodlvl ); //тут ваш массив кладем в массив другой массив $account_array = array( 'account' => $arr ); //заметьте тут поменялся массив источник вместо $arr мы кодируем в json $account_array file_put_contents($name, json_encode($account_array, JSON_UNESCAPED_UNICODE)); 
  • thanks) it’s strange that I didn’t think of it before, although I tried to create something like this - newArray