将PHP响应对象转换为Javascript对象

时间:2018-10-10 12:47:10

标签: javascript php arrays dom

我试图将javascript调用为PHP服务。然后,我从该服务获得响应。 但是,现在我需要将该响应对象转换为JSON对象。

我的PHP服务,

if ( isset($_POST['S3']) && ($_POST['S3'] == 'true' || $_POST['S3'] == 'TRUE')){
$result = $client->detectLabels([
    'Image' => [ 
        'S3Object' => [
            'Bucket' => 'spiralup',
            'Name' => ''.$filename
        ],
    ],
    'MaxLabels' => 10,
    'MinConfidence' => 60
]);
}else {
    $result = $client->detectLabels([
        'Image' => [ 
            'Bytes' => $contents
        ],
        'MaxLabels' => 10,
        'MinConfidence' => 60
    ]);
}
//echo($result);

//echo $result->getPath('Labels/Name');
//> ACTIVE

// Convert the Model to a plain array
var_export($result->toArray()['Labels']);

我的Javascript代码

var form = new FormData();
form.append("imagePath", "D:\\xampp\\htdocs\\webcam\\webcamImage\\20181009091628.jpg");
form.append("S3", "false");

var settings = {
  "async": true,
  "crossDomain": true,
  "url": "http://localhost:90/AWS_Test.php?Content-Type=application/json",
  "method": "POST",
  "headers": {},
  "processData": false,
  "contentType": false,
  "mimeType": "multipart/form-data",
  "data": form
}

$.ajax(settings).done(function (response) {
  console.log(response);
});

这里,我的样本响应对象。

      array (
        0 => 
        array (
          'Name' => 'Sathish',
          'Id' => 91,
        ),
        1 => 
        array (
          'Name' => 'Anish',
          'Id' => 92,
        ),
        2 => 
        array (
          'Name' => 'Anil',
          'Id' => 99,
        ),
        3 => 
        array (
          'Name' => 'Chennai',
          'Id' => 69,
        ),
        4 => 
        array (
          'Name' => 'Beard',
          'Id' => 64,
        ),
      )

但是我需要这样,

[   {
        "0":[{"Name" : "Sathish", "Id" : 91}], 
        "1":[{"Name" : "Anish", "Id" : 92}], 
        "2":[{"Name" : "Anil", "Id" : 99}], 
        "3":[{"Name" : "Chennai", "Id" : 69}], 
        "4":[{"Name" : "Beard", "Id" : 64}]
    }
]

预先感谢,如果您投了反对票,请告诉我原因。

2 个答案:

答案 0 :(得分:0)

var_export交换json_encode,这应该可以完成工作:

json_encode($result->toArray()['Labels']);

文档:http://php.net/manual/en/function.json-encode.php

答案 1 :(得分:0)

为什么不使用此模型?

$arr=array(
    array(
        'name'=>'test1',
        'id'=>'1',
    ),
    array(
        'name'=>'test2',
        'id'=>'2',
    ),
    array(
        'name'=>'test3',
        'id'=>'3',
    ),

);
echo json_encode($arr); ///[{"name":"test1","id":"1"},{"name":"test2","id":"2"},{"name":"test3","id":"3"}]