多次编码json值

时间:2018-04-22 01:00:08

标签: php arrays json

我有一个Web表单,在提交时运行此php并创建文件webtest1.json。我需要动画数组重复多次相同的值,但目前,我似乎只是获得最后一个值。我想实现:

"animation": {
        "typename": "split",
        "size": 6,
        "animations": [
            {"typename": "BiblioPixelAnimations.strip.ColorChase.ColorChase",
                "color": "Red"},
            {"typename": "BiblioPixelAnimations.strip.ColorChase.ColorChase",
                "color": "Blue"},
            {"typename": "BiblioPixelAnimations.strip.ColorChase.ColorChase",
                "color": "Red"},
            {"typename": "BiblioPixelAnimations.strip.ColorChase.ColorChase",
                "color": "Blue"},
            {"typename": "BiblioPixelAnimations.strip.ColorChase.ColorChase",
                "color": "Red"},
            {"typename": "BiblioPixelAnimations.strip.ColorChase.ColorChase",
                "color": "Blue"}
        ]





            },

目前PHP正如此

<?php
if( !empty( $_POST ) ){
$postArray = array(
  "driver" => $_POST['driver'],
  "animation" => array(
     "typename" => $_POST["typename"],
     "size" => intVal($_POST["size"]),
     "animations" => array(array(
        "typename" => $_POST["typename2"],
        "color" => $_POST["colorA"],
        "typename" => $_POST["typename2"],
        "color" => $_POST["colorB"],
        "typename" => $_POST["typename2"],
        "color" => $_POST["colorA"],
        "typename" => $_POST["typename2"],
        "color" => $_POST["colorB"],
        "typename" => $_POST["typename2"],
        "color" => $_POST["colorA"],
        "typename" => $_POST["typename2"],
        "color" => $_POST["colorB"]
        ),
        )
    ),
"run" => array(
     "fps" => intVal($_POST["fps"])
    ),
"layout" => $_POST['layout']    
); //Check the fiels array is correct
$json = json_encode( $postArray );
$file = '/home/pi/Documents/webtest1.json';
file_put_contents( $file, $json);
}   
shell_exec("sudo killall -HUP bp");
$running = fopen("/home/pi/Documents/runningeffect.txt", "w");
fwrite($running,"A Split Chase");
fclose($running);
header("Location: /");
?>

我错过了什么?运行Apache 2.4.25&amp; Raspberry Pi上的PHP 7.0.27

1 个答案:

答案 0 :(得分:0)

每个typename / color对都需要是一个数组

"animations" => array(
  array(
    "typename" => $_POST["typename2"],
    "color" => $_POST["colorA"]
  ),
  array(
    "typename" => $_POST["typename2"],
    "color" => $_POST["colorB"]
  ),
  array(
    "typename" => $_POST["typename2"],
    "color" => $_POST["colorA"]
  ),
  array(
    "typename" => $_POST["typename2"],
    "color" => $_POST["colorB"]
  ),
  array(
    "typename" => $_POST["typename2"],
    "color" => $_POST["colorA"]
  ),
  array(
    "typename" => $_POST["typename2"],
    "color" => $_POST["colorB"]
  )
)