dongzhao5834 2018-06-13 02:55
浏览 47
已采纳

PHP Javascript - 数组多维错误

In practice, I create an array in PHP that then I pass to a JavaScript function.

So far so good. The array that the functions recieves is the following:

[[{"firstname": "Micheal", "lastname": "Brown"}], [{"car": "Ford", "model": "Fiesta"}]]

My problem is to get all the first array, that is this: {"firstname": "Micheal", "lastname": "Brown"}

and also the second array this: {"car": "Ford", "model": "Fiesta"}

I tried with alert (array [0]) but it only shows me this [

How can I do this?

I'll explain:

this is my php file:

class UserClasses
{
     public $firstname;
     public $lastname;
}

class CarClasses
{
     public $car;
     public $model;
}

if(isset($_POST['name'])){
     populate($_POST['name']);
}

function populate(){
//I abbreviated the function for simplicity

   $arrayUser = array();
   $arrayCar = array();

   $user = new UserClasses();
   $user->firstname = "Micheal";
   $user->lastname = "Brown";
   array_push($arrayUser, $user);

   $car = new CarClasses();
   $car->car = "Ford";
   $car->model = "Fiesta";
   array_push($arrayCar, $car);
   $arrayFinal = array($arrayUser, $arrayCar);

   print json_encode($arrayFinal);
}

and this is the function in javascript:

//Ajax for calling php function
$.post('Classes.php', { name: name }, function(data){
    var array = JSON.parse(data);
    var arrayT = array[0];
    alert(arrayT);
});

展开全部

  • 写回答

4条回答 默认 最新

  • dtujfmfs06058 2018-06-13 03:02
    关注

    Here's what is happening with your code: you're accessing the first element of a JSON string, so my guess is you will get its first character: [.

    You need to convert your string into an actual array before accessing it!

    Use JSON.parse:

    The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string.

    - MDN web docs

    For example you can do:

    const json = '[[{"firstname": "Micheal", "lastname": "Brown"}], [{"car": "Ford", "model": "Fiesta"}]]'
    
    // that's what you have
    console.log(json[0])
    
    // that's what you want
    array = JSON.parse(json)
    console.log(array[0])

    </div>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部