如何将多维数组解析为PHP

时间:2017-02-23 03:23:51

标签: javascript php arrays parsing multidimensional-array

我试图将一个多维数组发布到php,但我没有运气 我的数组是在包含数组/对象的Javascript中创建的,并且在每个数组中都是一个关联的值,例如它已完成 在这个功能:

function mouseUp(e) {
    startX = 0;
    startY = 0;
    endX = e.pageX - this.offsetLeft;
    endY = e.pageY - this.offsetTop;
    width = 30;
    height = 30;
    filler = "#FFFFFF";
    filler = "#FFFF00";
    //send these vars over and push them into an array
    addRect(startX, startY, width, height, filler, border);
} //end on mouse up

function addRect(startx, starty, endX, endY, color1, bc) {

    newArray2 = [{
        x: startx,
        y: starty,
        x1: endX,
        y1: endY,
        color: color1,
        borderColor: bc
    }];
    arrayBig.push(newArray2);

    //console.log(arrayBig);
}

我使用此函数来定位输入值,如:

function send() {

    var elem = document.getElementById("rectangle");
    var myJSON = JSON.stringify(arrayBig);
    elem.value = myJSON;
}

我的html表单是这样的:

<form action="#" enctype="multipart/form-data" method="post" >
<input name="rectangle[][]" id="rectangle" type="hidden" class="valueFields" value=""/>
<input name="parseMe" type="hidden" value="layout" />
<input type="submit" name="button" id="submitButton" value="send" onclick="send()"/>
</form>

现在我在这部分遇到了麻烦,在这里将数组值分配给PHP中的变量:

<?php
if (isset($_POST['parseMe'])) {
    if ($_POST['parseMe'] == "layout") {
        print_r($_POST['rectangle']);
$myObj= json_decode($POST['rectangle'],true);
echo $myObj['color'];
        //how to assign each value to a variable here???
        //$x = rectangle[0][0].color; //doesn't work
    }
}
?>

如果有人能告诉我如何妥善解析这一点,我会提前感谢你 在Javascript中我需要做的就是将值赋给var是这样的:      c = arrayBig [0] [0] .color;

但是我如何在PHP中使用这行代码呢? 输入名称也会看起来像name =&#34; rectangle []&#34;或name =&#34; rectangle [] []&#34; ?

1 个答案:

答案 0 :(得分:0)

我想我找到了你要找的东西。

表单传输后你的post数组看起来像这样:

$_POST['rectangle'] = "[{\"startx\": \"1\", \"starty\": \"2\"}]"

我认为在这个简短的剧本后你会说它有多容易:

$jsonString = filter_input(INPUT_POST, 'rectangle');
$objectArray = json_decode($jsonString);
foreach($objectArray as $key => $singleObject){
  echo $singleObject->startx; // output is 1
  echo $singleObject->starty; // output is 2
);