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 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值