Mahdi Nouri Mahdi Nouri - 2 months ago 10
PHP Question

adding json array in a specific scope with php

I'm adding a json array with php and a html form

my form :

<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
</head>
<body>
<form action="process.php" method="POST">
maddahImage<br>
<input type="text" name="maddahImage">
<br><br/>
maddahName:<br>
<input type="text" name="maddahName">
<br><br>

maddahFolder:<br>
<input type="text" name="maddahFolder">
<br><br>

<input type="submit" value="Submit">
</form>
</body>
</html>


my php:

<?php

$myFile = "maddah";
$arr_data = array("maddahs"); // create empty array

try
{
//Get form data
$formdata = array(
'maddahImage'=> $_POST['maddahImage'],
'maddahName'=> $_POST['maddahName'],
'maddahFolder'=>$_POST['maddahFolder']
);

//Get data from existing json file
$jsondata = file_get_contents($myFile);

// converts json data into array
$arr_data = json_decode($jsondata, true);

// Push user data to array
array_push($arr_data,$formdata);

//Convert updated array to JSON
$jsondata = json_encode($arr_data, JSON_PRETTY_PRINT);

//write json data into data.json file
if(file_put_contents($myFile, $jsondata)) {
echo 'Data successfully saved';
}
else
echo "error";
}
catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}

?>


it's working fine my problem is to add this new array in a specific scope, not to create a new scope

something like this:

{
"maddahs": [
{
"maddahImage": "http://www.zakerin.ir/uploads/category/0542bc127d4656-55.jpg",
"maddahName": "TEST",
"maddahFolder" : "JafarImanNejad"
},
{
"maddahImage": "http://www.zakerin.ir/uploads/category/0542bc127d4656-55.jpg",
"maddahName": "TEST1",
"maddahFolder" : "JafarImanNejad1"
}
]
}


but this php saves new array like this:

{
"maddahs": [
{
"maddahImage": "http:\/\/www.zakerin.ir\/uploads\/category\/0542bc127d4656-55.jpg",
"maddahName": "\u062c\u0639\u0641\u0631 \u0627\u06cc\u0645\u0627\u0646 \u0646\u0698\u0627\u062f",
"maddahFolder": "JafarImanNejad"
}
],
"0": {
"maddahImage": "TESTIMAGE",
"maddahName": "TESTNAME",
"maddahFolder": "TESTTEST"
}
}

Answer

Try this

// Push user data to array
   array_push($arr_data['maddahs'],$formdata);

It's a multidimensional array, so you need to address the right array, the one inside $arr_data['maddahs'].