使用php在特定范围内添加json数组

使用php在特定范围内添加json数组,php,json,forms,Php,Json,Forms,我正试图用PHP和HTML表单向现有的JSON数组添加一个JSON对象 我的php文件: <?php $myFile = "someFile"; $arr_data = array("myArray"); // create empty array try { //Get form data $formdata = array( 'someImage'=> $_POST['someImage'

我正试图用PHPHTML表单向现有的JSON数组添加一个JSON对象

我的php文件:

<?php

    $myFile = "someFile";
    $arr_data = array("myArray"); // create empty array

    try
    {
        //Get form data
        $formdata = array(
            'someImage'=> $_POST['someImage'],
            'someName'=> $_POST['someName'],
            'someFolder'=>$_POST['someFolder']
        );

        //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";
    }

?>
但这是我从上述代码中得到的:

{
    "myArray": [
        {
            "someImage": "imageUrl",
            "someName": "TEST",
            "someFolder": "folderName"
        }
    ],
    "0": {
        "someImage": "TESTIMAGE",
        "someName": "TESTNAME",
        "someFolder": "TESTTEST"
    }
}
试试这个

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

这是一个多维数组,因此您需要处理正确的数组,即
$arr_data['maddahs']

没有“JSON数组”或“JSON对象”这样的东西。是某些数据结构(通常是对象或数组,但标量值也可以编码为JSON)的文本表示形式。作为文本,JSON只能存储(在文件、数据库等中)或通过网络发送。必须对其进行解码,才能返回与创建数据结构类似的数据结构,并且该数据结构(无论是数组、对象还是其他)不是JSON。您的代码很好地处理JSON,这个问题与JSON完全没有关系。您需要阅读@axiac这是一个老问题。我刚修正了一些打字错误。它在新问题页面上吗?的确,它是旧的。我没有注意到。您在10分钟前更新了它,因此尽职尽责地将其显示在“最新”页面上(其中不仅显示新问题,还显示最近有活动的问题)。
// Push user data to array
   array_push($arr_data['maddahs'],$formdata);