javascript - 将js文件中的数组Fatch到php中,然后编码成json

标签 javascript php arrays json

我有一个js文件,其中包含一些数组形式的数据。 http://localhost/js/data.js 信息类似于

var subjectCodeArray=["CS/ Computer Science","AF/ Art Facalty",...]; 

我想将数组“subjectCodeArray”中的信息获取到我的php文件“subjectCode.php”中,然后将其编码为json数组。 我不知道该怎么做,请帮我做一下。

提前致谢......

最佳答案

我首先得到了答案,从js文件中获取数据 $data = file_get_contents("./data.js");

Create a substring which contain the data from starting "[" to the ending "]"
$substrdata = substr($data, strpos($data,'[')+1, strpos($data,']') - strpos($data,'['));

then replase "\" with space
$substrdata = str_replace("\"", "", $substrdata);

then replace the singal cotes
$substrdata = str_replace("'", "", $substrdata);

and the explode it in the bases of comma and store it in array 
$arr=explode(",",$substrdata);
$json_response = array();

for($i=0;$i<count($arr);$i++)
{
    $row_array['student'] = preg_replace("/\//",'',$arr[$i]);
    array_push($json_response,$row_array);
}

最后编码为json形式 $output = json_encode(array('student_info'=>$json_response)); 回显$输出;

关于javascript - 将js文件中的数组Fatch到php中,然后编码成json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31317160/

相关文章:

php - XAMPP-Magento-错误 : pdo_mysql

javascript - 使用 JSON 填充全局数组

javascript - 使用 JavaScript (Ember.js) 将 TMDb 中的流派 ID 与流派名称进行匹配

javascript - 在我的 html 中包含 event.keycode == 13 后 &lt;textarea&gt; 换行不起作用

JavaScript 算法未正确过滤

php - stripslashes 对 SQL 注入(inject)的有效性?

arrays - 获取数组 bash 的随机元素的函数

javascript - 通过 JavaScript 获取页面/iframe 的编码

javascript - 如何根据用户的输入更改 html 元素的值?

php - 如何从 PHP 中的多维数组中删除重复值