繁体   English   中英

将php数组转换为javascript数组

[英]converting php array into javascript array

我正在尝试根据2个不同的代码段创建词云。 一个返回一个包含单词和每个单词的权重的数组,而第二个则采用该数组并创建单词云。 但是,我不确定如何将php数组转换为javascript数组。

php数组代码:

<?php
$arr = *data from database*;
$string = implode(",", $arr);
error_reporting(~E_ALL);
$count=0;
//considering line-return,line-feed,white space,comma,ampersand,tab,etc... as word separator
$tok = strtok($string, " \t,;.\'\"!&-`\n\r");
if(strlen($tok)>0) $tok=strtolower($tok);
    $words=array();
    $words[$tok]=1;

    while ($tok !== false) {
        //echo "Word=$tok<br />";
        $tok = strtok(" \t,;.\'\"!&-`\n\r");
        if(strlen($tok)>0) {
            $tok=strtolower($tok);

            if($words[$tok]>=1){
                $words[$tok]=$words[$tok] + 1;
            } else {
                $words[$tok]=1;
            }
        }
    }

当回显时,它将返回这样的数组。 数组([checking] => 1)

而javascript采用这种形式的数组:

var word_list = [
          {text: "Lorem", weight: 15},
          {text: "Ipsum", weight: 9, url: "http://jquery.com/", title: "I can haz URL"},
          {text: "Dolor", weight: 6},
          {text: "Sit", weight: 7},
          {text: "Amet", weight: 5}
          // ...other words
      ];

我如何for循环php数组以替换为text和weight变量?

任何帮助,将不胜感激。 让我知道您是否需要用于创建php数组的代码。

应该这样做(放在您当前的代码之后):

$cloud = Array();
foreach ($words as $text => $weight) {
    $cloud[] = Array('text' => $text, 'weight' => $weight);
}
echo json_encode($cloud);

它不考虑给定JS示例中urltitle等的可能性,但是我认为这是您所追求的。 这是一个演示: http : //codepad.org/OnEDIe1l

当然,您可以调整构建$words数组的PHP来构建它,使其已经与我的代码在$cloud生成的内容匹配。 但是也许您需要使用$words来做其他事情...(而且我可以看到在使用您当前拥有的代码进行标记化期间维护计数变得更加容易)。

您可以使用json_encode

$a = array("a" => 1, "b" => 2);
print json_encode($a);

输出: {"a":1,"b":2}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM