I am trying to create a word cloud based on 2 different pieces of code. One returns an array with the words and the weight for each word while the second piece takes in this array and creates the word cloud. However, I am not sure how to convert the php array to a javascript array.
The php array code:
<?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;
}
}
}
This returns an array such as this when echoed.
Array ( [checking] => 1 )
while the javascript takes in array in this form:
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
];
How do I for loop the php array to replace into the text and weight variables?
Any help would be appreciated. Let me know if you need the code for the creation of php array.
This should do it (placed after your current code):
It doesn’t account for the possibility of
url,title, etc in your given JS sample, but I think it’s what you’re after. Here’s a demo: http://codepad.org/OnEDIe1lOf course, you could just adjust the PHP which builds your
$wordsarray to build it such that it already matches what my code produces in$cloud. But maybe you need to do other things with$words… (and I can see how it’s easier to maintain a count during tokenization with the code you currently have).