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

时间:2017-09-03 17:50:08

标签: javascript php arrays json

目前我正在从Javascript执行POST操作到PHP文件以在PHP中执行操作并获得响应,但是在php文件中我有数组并且我想将它作为JSON数组接收到JavaScript如何可以我这样做

Java脚本

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

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;
  }

}
?>

现在我想将这些发送到Javascript作为JSONArray

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

任何人请在这里帮忙

我已经提到了以下所有内容,但没有多少帮助

Link 1

Link 2

3 个答案:

答案 0 :(得分:2)

试试这个:

<?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);

?>

如您所见,第一个样本具有未转义的unicode

输出:

[{&#34;名称&#34;:&#34;中&#34;&#34;年龄&#34;:30,&#34;车&#34;:空},{&# 34;名称&#34;:&#34;麦克&#34;&#34;年龄&#34;:32,&#34;车&#34;:空}] [{&#34;名称&#34;:&#34; \ u4e2d&#34;&#34;年龄&#34;:30,&#34;车&#34;:空},{&#34;名称& #34;:&#34;麦克&#34;&#34;年龄&#34;:32,&#34;车&#34;:空}]

答案 1 :(得分:1)

  

现在我想将这些发送到Javascript,如下面的JSONArray

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

确定首先设置php数组:

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

然后json在php中对其进行编码

echo  json_encode($myarray);

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

有关使用json从php发送json响应的正确方法的更多详细信息,请查看:Returning JSON from a PHP Script

答案 2 :(得分:1)

如果您希望在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}]"

参见示例here

对于json编码的PHP对象数组,它需要用单引号括起来,然后用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>

查看有用的资源here和此discussion