如何将PHP数组作为JSON数组传递给Javascript

时间:2022-10-17 09:30:06

Currently I am doing the POST Operation to PHP file from the Javascript to perform the operation in PHP and get the response, But in the php file I am having the Array and I wanted to receive it to JavaScript as JSON Array How Can I do that

目前,我正在从Javascript对PHP文件进行POST操作,以执行PHP中的操作并获得响应,但是在PHP文件中,我有一个数组,我想将它作为JSON数组接收到Javascript

Java Script

Java脚本

$scope.details = function() {
  $http({
    method: 'POST',
    url: 'myjson.json'
  }).then(function(response) 
  })

PHP Code

PHP代码

 <?php

header('Content-Type: application/json');
// index.php
// Run the parallel get and print the total time
$s = microtime(true);
// Define the URLs
$urls = array(
  "url1",
  "url2",
  "url3"
);
$pg = new ParallelGet($urls);
//print "<br />total time: ".round(microtime(true) - $s, 4)." seconds";

// Class to run parallel GET requests and return the transfer
class ParallelGet
{
  function __construct($urls)
  {
    // Create get requests for each URL
    $mh = curl_multi_init();
    $headers = array(
    'authorization: Basic xyz',
    'cache-control' => 'no-cache',
    'Accept:application/json'
  );
    foreach($urls as $i => $url)
    {
      $ch[$i] = curl_init($url);
      curl_setopt($ch[$i], CURLOPT_SSL_VERIFYHOST, 0);
      curl_setopt($ch[$i], CURLOPT_SSL_VERIFYPEER, 0);
      curl_setopt($ch[$i], CURLOPT_RETURNTRANSFER, 1);
      curl_setopt($ch[$i], CURLOPT_HTTPHEADER, $headers);
      curl_multi_add_handle($mh, $ch[$i]);
    }

    // Start performing the request
    do {
        $execReturnValue = curl_multi_exec($mh, $runningHandles);
    } while ($execReturnValue == CURLM_CALL_MULTI_PERFORM);
    // Loop and continue processing the request
    while ($runningHandles && $execReturnValue == CURLM_OK) {
      // Wait forever for network
      $numberReady = curl_multi_select($mh);
      if ($numberReady != -1) {
        // Pull in any new data, or at least handle timeouts
        do {
          $execReturnValue = curl_multi_exec($mh, $runningHandles);
        } while ($execReturnValue == CURLM_CALL_MULTI_PERFORM);
      }
    }

    // Check for any errors
    if ($execReturnValue != CURLM_OK) {
      trigger_error("Curl multi read error $execReturnValue\n", E_USER_WARNING);
    }

    // Extract the content
    foreach($urls as $i => $url)
    {
      // Check for errors
      $curlError = curl_error($ch[$i]);
      if($curlError == "") {
        $res[$i] = curl_multi_getcontent($ch[$i]);
        //$finalResponse[] = $res[$i]->load();
      } else {
        print "Curl error on handle $i: $curlError\n";
      }
      // Remove and close the handle
      curl_multi_remove_handle($mh, $ch[$i]);
      curl_close($ch[$i]);

    }
    // Clean up the curl_multi handle
    curl_multi_close($mh);
      //print_r($res);
    $responseArray = $res;
    // Print the response data

  $responseMSO = json_encode($res);
//print_r(utf8_encode(json_encode($res)));
  //echo $finalResponse[1];
  //echo $responseMSO;
  }

}
?>

Now I want to send these to Javascript as JSONArray

现在我想把这些作为JSONArray发送给Javascript

I have seen the suggestion to use json_encode in PHP but when I use that I am getting response as utf-encoded.

我已经看到在PHP中使用json_encode的建议,但是当我使用它时,我得到的响应是utf编码的。

Any one please help here

谁来帮忙

I have referred all the below but didn't help much

我已经提到了下面所有的内容,但是没有什么帮助

Link 1

链接1

Link 2

链接2

3 个解决方案

#1


2  

Try this:

试试这个:

<?php 

$myarray = array('{ "name":"中", "age":30, "car":null }','{ "name":"Mike", "age":32, "car":null }');
foreach ($myarray as $array) {
    $arrays[] = json_decode($array);
}

echo json_encode($arrays, JSON_UNESCAPED_UNICODE);
echo '<br>';
echo json_encode($arrays);

?>

As you can see the first sample has unescaped unicode

如您所见,第一个示例没有转义unicode

OUTPUT:

输出:

[{"name":"中","age":30,"car":null},{"name":"Mike","age":32,"car":null}] [{"name":"\u4e2d","age":30,"car":null},{"name":"Mike","age":32,"car":null}]

[{“名称”:“中”,“年龄”:30,“车”:零},{“名称”:“迈克”,“年龄”:32岁的“汽车”:零}][{“名称”:“\ u4e2d”,“年龄”:30,“车”:零},{“名称”:“迈克”,“年龄”:32岁的“汽车”:零}]

#2


1  

Now I want to send these to Javascript as JSONArray like below

现在我想把它们发送到Javascript,像下面这样的JSONArray。

[{ "name":"John", "age":30, "car":null },{ "name":"Mike", "age":32, "car":null }]

[{“名称”:“约翰”,“年龄”:30,“车”:零},{“名称”:“迈克”,“年龄”:32岁的“汽车”:零}]

OK so set up php array first:

首先设置php数组

$myarray = array(
        array(
            'name' => 'John',
            'age'  => 30,
            'car'  => null
        ),
        array(
            'name' => 'Mike',
            'age'  => 32,
            'car'  => null
        )
);

then json encode it in php

然后json用php进行编码

echo  json_encode($myarray);

Result:[{"name":"John","age":30,"car":null},{"name":"Mike","age":32,"car":null}]

结果:[{“名称”:“约翰”,“年龄”:30,“车”:零},{“名称”:“迈克”,“年龄”:32岁的“汽车”:零}]

For more details on proper way to send a json response from php using json take a look at this: Returning JSON from a PHP Script

有关使用json从php发送json响应的正确方式的详细信息,请查看以下内容:从php脚本返回json

#3


1  

If you wish to convert an array of objects in PHP and have it JSON-encoded so that JavaScript can use the result, here's one way to accomplish that feat:

如果您希望转换PHP中的对象数组,并对其进行json编码,以便JavaScript可以使用结果,这里有一种方法可以实现这一壮举:

<?php


$o = new stdClass;
$o->name = "John";
$o->age = 30;
$o->car =null;

$o2 = new stdClass;
$o2->name = "Mike";
$o2->age = 32;
$o2->car =null;

$myarray = [$o, $o2];

var_dump(json_encode($myarray));

// result:
 "[{"name":"John","age":30,"car":null},{"name":"Mike","age":32,"car":null}]"

see example here.

看到的例子。

For the json-encoded PHP array of objects to be useful for JavaScript it needs to be enclosed in single quotes and then parsed with JSON, as follows:

要使JSON编码的PHP对象数组对JavaScript有用,需要用单引号括起来,然后用JSON解析,如下所示:

<script language="JavaScript">
var obj = JSON.parse('<?php echo json_encode($myarray) ?>');
console.log(obj[0].name + "\t" + obj[1].name); // John   Mike
</script>

See useful resource here and this discussion.

请参阅这里的有用资源和本讨论。

#1


2  

Try this:

试试这个:

<?php 

$myarray = array('{ "name":"中", "age":30, "car":null }','{ "name":"Mike", "age":32, "car":null }');
foreach ($myarray as $array) {
    $arrays[] = json_decode($array);
}

echo json_encode($arrays, JSON_UNESCAPED_UNICODE);
echo '<br>';
echo json_encode($arrays);

?>

As you can see the first sample has unescaped unicode

如您所见,第一个示例没有转义unicode

OUTPUT:

输出:

[{"name":"中","age":30,"car":null},{"name":"Mike","age":32,"car":null}] [{"name":"\u4e2d","age":30,"car":null},{"name":"Mike","age":32,"car":null}]

[{“名称”:“中”,“年龄”:30,“车”:零},{“名称”:“迈克”,“年龄”:32岁的“汽车”:零}][{“名称”:“\ u4e2d”,“年龄”:30,“车”:零},{“名称”:“迈克”,“年龄”:32岁的“汽车”:零}]

#2


1  

Now I want to send these to Javascript as JSONArray like below

现在我想把它们发送到Javascript,像下面这样的JSONArray。

[{ "name":"John", "age":30, "car":null },{ "name":"Mike", "age":32, "car":null }]

[{“名称”:“约翰”,“年龄”:30,“车”:零},{“名称”:“迈克”,“年龄”:32岁的“汽车”:零}]

OK so set up php array first:

首先设置php数组

$myarray = array(
        array(
            'name' => 'John',
            'age'  => 30,
            'car'  => null
        ),
        array(
            'name' => 'Mike',
            'age'  => 32,
            'car'  => null
        )
);

then json encode it in php

然后json用php进行编码

echo  json_encode($myarray);

Result:[{"name":"John","age":30,"car":null},{"name":"Mike","age":32,"car":null}]

结果:[{“名称”:“约翰”,“年龄”:30,“车”:零},{“名称”:“迈克”,“年龄”:32岁的“汽车”:零}]

For more details on proper way to send a json response from php using json take a look at this: Returning JSON from a PHP Script

有关使用json从php发送json响应的正确方式的详细信息,请查看以下内容:从php脚本返回json

#3


1  

If you wish to convert an array of objects in PHP and have it JSON-encoded so that JavaScript can use the result, here's one way to accomplish that feat:

如果您希望转换PHP中的对象数组,并对其进行json编码,以便JavaScript可以使用结果,这里有一种方法可以实现这一壮举:

<?php


$o = new stdClass;
$o->name = "John";
$o->age = 30;
$o->car =null;

$o2 = new stdClass;
$o2->name = "Mike";
$o2->age = 32;
$o2->car =null;

$myarray = [$o, $o2];

var_dump(json_encode($myarray));

// result:
 "[{"name":"John","age":30,"car":null},{"name":"Mike","age":32,"car":null}]"

see example here.

看到的例子。

For the json-encoded PHP array of objects to be useful for JavaScript it needs to be enclosed in single quotes and then parsed with JSON, as follows:

要使JSON编码的PHP对象数组对JavaScript有用,需要用单引号括起来,然后用JSON解析,如下所示:

<script language="JavaScript">
var obj = JSON.parse('<?php echo json_encode($myarray) ?>');
console.log(obj[0].name + "\t" + obj[1].name); // John   Mike
</script>

See useful resource here and this discussion.

请参阅这里的有用资源和本讨论。