开发者

php array not forming properly

开发者 https://www.devze.com 2023-01-23 03:38 出处:网络
Initial javascript to get a string/array: <script type=\"text/javascript\"> $(document).ready(function() {

Initial javascript to get a string/array:

<script type="text/javascript">
$(document).ready(function() {
    $("#table").tableDnD({
    onDrop: function(table, row){
        var rows = table.tBodies[0].rows;
            var debugStr = "";
            for (var i=1; i<rows.length; i++) {
                debugStr += rows[i].id+":";
                //debugStr += rows[i].id;
            }
        data = debugStr; // colon seperated
        }
    });
});
function sendData()
{
    var packed = ""; // Initialize packed or we get the word 'undefined'
    for (i = 0; (i < data.length); i++) {
    if (i > 0) {
        packed += ",";
        }
    packed += escape(data[i]);
        }
    document.data.data.value = packed;
    document.data.submit();
}
</script>

Now in the PHP...

Return my array/string from post:

$packed = $_POST['data'];
$data = split(":", $packed);
for ($i = 0; ($i < count($data)); $i++) {
  $data[$i] = rawurldecode($data[$i]);
  $data[$i] = str_replace(",", "", $data[$i]);
  $data[$i] = str_replace(":", ",", $data[$i]);
}

create an array from it:

$arrayUpdated = array();
foreach($data as $value)开发者_C百科 {
    print_r($value);
    $arrayUpdated[] = $value;
    }

which returns:

Array ( [0] => 9,8,6,5,4,3,2,15,1,0, ) 

when I was expecting:

Array ( [0] => 9, [1] => 8, [2] => 6, [3] => 5, [4] => 4, [5] => 3, [6] => 2, [7] => 15, [8] => 1, [9] => 0, ) 

what have I got wrong? Thanks, Andy


Since you're using JQuery already, wouldn't it be easier to send the data in JSON format rather than manually building it into a colon/comma separated and then manually spliting it apart in PHP?

In your JS page, replace most of your sendData() function with a call to $.toJSON(data);:

function sendData() {
    document.data.data.value = $.toJson(data);
    document.data.submit();
}

In your PHP code, simlpy use json_decode() to load your data into an array with exactly the same structure as you had in Javascript.

$data=json_decode($_POST['data']);
print_r($data);

*Note: you may need an extra JQuery plugin to get the toJSON() method -- See http://code.google.com/p/jquery-json/ for more info.


Not a direct answer- but if you need a quick fix you could do (in PHP):

// if $myarray=Array ( [0] => 9,8,6,5,4,3,2,15,1,0, ) ;

$myarray=explode(",",$myarray[0]);

Also, note that the split function is deprecated in PHP 5.3.0, you can replace with explode.

0

精彩评论

暂无评论...
验证码 换一张
取 消