【问题标题】:Import php array into javascript dataset将php数组导入javascript数据集
【发布时间】:2015-08-06 08:44:05
【问题描述】:

我提取了一些数据并将它们组织在 .php 文件中的数组中。

现在我想在另一个扩展名为 .html 的文件中使用 d3 方法可视化该数据。我想将该数组导入数据集中。

我将尝试在此处发布代码或有意义的内容:

<?php

        // data extraction from a bunch of xml files.
        // stored all of that in an array ---- $topics 
        // sorted the array by frequency of the elements 

        $topic_count = array_count_values($topics);

        echo '<p>' . "Array Testing " . '</p>';

        foreach ($newArray as $key => $value) {
                echo "$key - <strong>$value</strong> <br />"; 
        }

    ?>

foreach 的输出是:

tim harper published - 5
TIM HARPER Published - 3
Updated - 1
Illustration Garnotte - 1
cour rejette - 1
cour supr me rejette les peines obligatoires du gouvernement harper - 1
Chris Wattie - 1
Stephen Harper - 1
contenu publication - 1
information - 1
juif canadien - 1

当我做echo json_encode($newArray,JSON_PRETTY_PRINT); 输出是:

{
    "tim harper published": 5,
    "TIM HARPER Published": 3,
    "Updated": 1,
    "Illustration Garnotte": 1,
    "cour rejette": 1,
    "cour supr me rejette les peines minimales obligatoires du gouvernement harper": 1,
    "Chris Wattie": 1,
    "Stephen Harper": 1,
    "contenu publication": 1,
    "information": 1,
    "juif canadien": 1
}

我已经尝试过:

script type = "javascript">
            var dataset = <?php echo json_encode($newArray,JSON_PRETTY_PRINT); ?>;
        </script>

但我无法获取要使用的数据。

似乎我在这里跑题了,但我的问题是如何在我的 html 文件中导入该数据。 (当然是同一个文件夹)

【问题讨论】:

  • 我认为son_encode 是错字?究竟是什么问题?为什么你的代码不起作用?
  • var dataset = JSON.parse(&lt;?php echo json_encode( $newArray, JSON_PRETTY_PRINT ); ?&gt;)
  • 是的,这是一个错字。修复它...我不知道它不起作用。
  • 我尝试将整个文件保存为 html 文件,但它只是打印代码。所以我决定在不同的 html 文件上执行 javascript,但我需要使用上面这段代码中的数据。
  • 效果不佳@Dendroaniac

标签: javascript php html arrays


【解决方案1】:

您可以将数据保存在文本文件中并进行解析。

var jsonphp = '<?php echo $d = file_get_contents("json.txt"); ?>';
var jsondata = $.parseJSON(jsonphp);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-24
    • 2021-11-01
    • 2016-02-16
    • 1970-01-01
    • 2011-02-20
    • 1970-01-01
    • 2017-11-27
    • 2011-01-27
    相关资源
    最近更新 更多