dongzhao5834 2018-06-13 10: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 11: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条)

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 如何将下列的“无限压缩存储器”设计出来
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口