首页 > 解决方案 > 使用 PHP 从 JSON 中检索数组

问题描述

$data_array = [
                ["","","","2",""],
                ["","1","","",""]
               ];
    $myJSONString = json_encode($data_array);
    $my = [
      "id"=> "1",
      "name" => "easy",
      "data" => $myJSONString,
     ];

  $myJSON_File->add($my);

我想在 JSON 中存储一个矩阵,然后检索它以稍后将其发送到 javascript 函数。我试过了,但是当我将它发送到 JS 函数时,矩阵作为字符串发送。我也尝试对其进行解码,$myArray = json_decode($output);但这也不起作用。

标签: javascriptphphtmljson

解决方案


将其作为字符串“发送”的方式是正确的,您只需解析字符串即可获得一个 javscript 对象/数组以像这样使用。

使用 json_encode 获取 php 文件中的字符串。

let string_example = '{"someVariable":"123"}'; //the string you retrieve from php
console.log(string_example);
let retrieved_obj = JSON.parse(string_example);
console.log(retrieved_obj.someVariable);


推荐阅读