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



我试图调用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}]
}
]

提前感谢,如果您投反对票,请告诉我原因。

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

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

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

为什么不使用这个模型?

$arr=数组( 数组( 'name'=>'test1', 'id'=>'1', ), 数组( 'name'=>'test2', 'id'=>'2', ), 数组( 'name'=>'test3', 'id'=>'3', ), ); 回声json_encode($arr(;[
{"name":"test1","id":"1"},{"name":"test2","id":"2"},{"name":"test3","id":"3"}]

最新更新