简体   繁体   中英

How do I get from JS array through JSON to a PHP array? (I'm at least halfway there)

I have a JS array, which I convert to JSON

JS

 mycode[0][0]=true
 mycode[0][1]="element1"
 mycode[0][2]=400
 mycode[0][3]=150
 mycode[0][4]=148
 mycode[0][5]=148

turned into JSON:

[
    [
        true,
        "element1",
        400,
        150,
        148,
        148
    ]

]

Now I push this to PHP

PHP code:

$decoded = json_decode($_GET["q"]);

$response=$q[0];

echo $response;

and it outputs a letter or a symbol as JSON was a string.

If I use $decoded[0][0] or $decoded[0] instead of $q[0] I get nothing...

What am I actually doing wrong?

What do I want? I need to have the same array I had in JS, just in PHP (the array will later be used in a PHP function)

Code:

<?php
$json = '[[ true,"element1",400,150,148,148 ]]';
$dec = json_decode($json);
var_dump($dec);
?>

Output:

array(1) {
  [0]=>
  array(6) {
    [0]=>
    bool(true)
    [1]=>
    string(8) "element1"
    [2]=>
    int(400)
    [3]=>
    int(150)
    [4]=>
    int(148)
    [5]=>
    int(148)
  }
}

Works fine here. Your problem must be somewhere else.

$ php -v
PHP 5.3.2 (cli) (built: Apr 27 2010 17:55:48) 
Copyright (c) 1997-2010 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2010 Zend Technologies

How are you pushing your JSON to the PHP code. When you pass your JSON to the PHP back-end, you should use a library such as json2.js to encode the content:

var myJSONText = JSON.stringify(myObject, replacer);

You may also need to URL-encode the JSON if you are passing it using GET.

抱歉,但在我看来,你需要阅读更多关于你想要使用的三件事,特别是AJAX和JSON

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM