Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
425 views
in Technique[技术] by (71.8m points)

php - Array values returns null

I am making post request with ajax and sending data with json format.Then I am fetching json with php and decode it into an array.When I print out whole array there is no problem. I can see the key value pairs.But when I try to print out this array's one of index value it returns null.What could be the problem?Here is my ajax request

$(function() {
    $("#del").click(function() {
        var file_id = 32
        var file_update = 1321321

        var obj = {
            file_id: file_id,
            file_update: file_update
        };

        $.ajax({
            type: "post",
            url: "config/ajax.php",
            data: {
                "file_update": JSON.stringify(obj)
            },
            success: function(response) {
                alert(response);
            }
        })
    })
})

Here is my php code

if (isset($_POST["file_update"])) {
    $file_update = json_decode($_POST["file_update"], true);
    $x = $file_update[0];
    var_dump($x);
    var_dump($file_update);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The $file_update array is associative, therefore it doesn't have integer keys, its keys are strings.

$file_update[0] does not exist and this statement should throw an error given you have proper error reporting configured.

If you want to access specific array values use:

$file_update['file_id'];
$file_update['file_update'];

If you want to access the first element of an associative array you can use the following:

$key = array_keys($file_update)[0];
$value = $file_update[$key];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...