繁体   English   中英

如何在PHP中访问JSON数组

[英]How to access JSON array in PHP

我试图通过ajax将多部分数组传递给PHP函数。

这是我的JS:

var datastring = {
        newEmailForm: newEmailForm,
        properties: properties
    };

    //got the data, make the ajax request
    jQuery(function(){
        jQuery.ajax({
            type:'POST',
            data:{
                action: 'elegantSendEmail',
                datastring: datastring
            },
            url: ajaxurl
        })
    })

这是要发送的数组:

action  elegantSendEmail
  datastring[newEmailForm][0][] {…}
    0   email
    1   title
    2   Message
  datastring[properties][0][]   {…}
    0   31466
    1   value1
    2   value1
  datastring[properties][1][]   {…}
    0   31440
    1   value2
    2   value2

这是我尝试通过PHP进行尝试的尝试,但我的响应中什么也没有。

function elegantSendEmail(){
   var_dump($_POST);
  wp_die();
}

这是从控制台进行转储的结果:

array(2) { 
  ["action"]=> string(16) "elegantSendEmail" 
  ["datastring"]=> array(1) { 
    ["newEmailForm"]=> array(1) { 
     [0]=> array(3) { 
      [0]=> string(5) "email" 
      [1]=> string(5) "title" 
      [2]=> string(17) "Youe message here" 
      } 
     } 
    } 
  } 

更多信息如何使用json_decode访问数据

$obj = json_decode($_POST['datastring']['newEmailForm'][0], true);

尝试这个

function elegantSendEmail() {
 $obj = $_POST['datastring']['newEmailForm'][0][0];
 var_dump($obj);
 //Above dump shows 'email'
 wp_die(); 
}

您需要在ajax中以正确的json格式发送数据。 例如

{
    "id": "0001",
    "type": "donut",
    "name": "Cake",
    "ppu": 0.55,
    "batters":
        {
            "batter":
                [
                    { "id": "1001", "type": "Regular" },
                    { "id": "1002", "type": "Chocolate" },
                    { "id": "1003", "type": "Blueberry" },
                    { "id": "1004", "type": "Devil's Food" }
                ]
        },
    "topping":
        [
            { "id": "5001", "type": "None" },
            { "id": "5002", "type": "Glazed" },
            { "id": "5005", "type": "Sugar" },
            { "id": "5007", "type": "Powdered Sugar" },
            { "id": "5006", "type": "Chocolate with Sprinkles" },
            { "id": "5003", "type": "Chocolate" },
            { "id": "5004", "type": "Maple" }
        ]
}

因此,根据您的答案以及$_POST结果在var_dump之后,我们看到您传递了一个数组而不是json对象。 因此,您可以像访问普通数组一样访问它的字段。

$obj=$_POST['datastring']['newEmailForm'][0][0]  // will get you the email

$obj=$_POST['datastring']['newEmailForm'][0][1]  // will get you the title

$obj=$_POST['datastring']['newEmailForm'][0][2]  // will get you the message

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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