如何用另一个数组推送JSON文件中的PHP数组

时间:2016-01-14 17:09:17

标签: php arrays json

我有一个名为“foods”的数组的JSON文件。在这个数组中,我想推送一个名称,类型和价格的新对象。

{
    "foods":[
        {
            "name": "Name1",
            "tyoe": "Type1",
            "price": "Price1"
        },
        {
            "name": "Name2",
            "type": "Type2",
            "price": "Price2"
        }
    ]
}

逻辑是:
我收到$ _POST的名称,类型和价格。 (这是一个简单的形式 - 它工作正常)
所以我想用PHP在JSON文件中的“foods”数组中推送这些数据。 结果是这样的:

{
    "foods":[
        {
            "name": "Name1",
            "tyoe": "Type1",
            "price": "Price1"
        },
        {
            "name": "Name2",
            "type": "Type2",
            "price": "Price2"
        },
        {
            "name": "NAME3",
            "type": "TYPE3",
            "price": "PRICE3"
        }
    ]
}

我正试图解决它的错误示例:

$name = $_POST['name'];
$type = $_POST['type'];
$price = $_POST['price'];

//Do I need to create this array to push inside JSON array "foods"?
$arrayFoods = array(        
    'name' => $name,
    'type' => $type,
    'price' => $price
);

$my_file = file_get_contents('database/file.json');

//Do I need to decode the JSON file to access the array "foods" to push my $arrayFoods? 
//How do I access the "foods" array in JSON file and push my $arrayFoods?
$fileDecode = json_decode($my_file);

谢谢!

1 个答案:

答案 0 :(得分:1)

按照你的所作所为

import alsaaudio   
import numpy as np
import array

# constants
CHANNELS    = 1
INFORMAT    = alsaaudio.PCM_FORMAT_FLOAT_LE
RATE        = 44100
FRAMESIZE   = 1024

# set up audio input
recorder=alsaaudio.PCM(type=alsaaudio.PCM_CAPTURE)
recorder.setchannels(CHANNELS)
recorder.setrate(RATE)
recorder.setformat(INFORMAT)
recorder.setperiodsize(FRAMESIZE)


buffer = array.array('f')
while <some condition>:
    buffer.fromstring(recorder.read()[1])

data = np.array(buffer, dtype='f')