prgrm
prgrm

Reputation: 3833

Copying and adding JSON schema as array in PHP

I am trying to add a copy of a key and its content to the JSON file by using php.

$content = file_get_contents($_POST["content"]);
$decode = json_decode($content,true);
$version = $_POST["version"];
array_unshift($decode['versions'],$version );
$encode = json_encode($decode,true);

Let's say we want to add the version 1.2.2. This adds:

...["versions"]=> array(6) { [0]=> string(5) "1.2.2" ["1.2.1"]=> array(4) { ["project"]=> string(21)...

instead of creating a 1.2.2 key and its sub arrays.

Also tried:

array_unshift($decode['versions'][$version],$version );

without results either

Upvotes: 0

Views: 241

Answers (1)

Noémi Salaün
Noémi Salaün

Reputation: 5036

If I undestand correctly, you can directly put the version inside your content like this :

$content = file_get_contents($_POST['content']);
$decode = json_decode($content, true);

$version = $_POST['version'];
$decode['version'] = $version;

$encode = json_encode($decode, true);

Upvotes: 1

Related Questions