我正在使用下面的代码,但我需要输出我的一些j son格式,如同Excepted output下面你能帮我解决一下我是怎么做到的,或者让我知道我在这里做错了什么
<?php
$text = "A very nice únÌcÕdë text. Something nice to think Something about if you're into Unicode.";
$words = str_word_count($text, 1); // use this function if you only want ASCII
$frequency = array_count_values($words);
arsort($frequency);
print_r($frequency);
?>
**Current output**
Array
(
[nice] => 2
[Something] => 2
[A] => 1
[very] => 1
[n] => 1
[c] => 1
[d] => 1
[text] => 1
[to] => 1
[think] => 1
[about] => 1
[if] => 1
[you're] => 1
[into] => 1
[Unicode] => 1
)
**Excepted output Below :**
{
{
‘word’ : ‘nice’
‘count’ : 2
‘rank’ : 1
},
{
‘word’ : ‘Something’
‘count’ : 2
‘rank’ : 2
},
{
‘word’ : ‘A’
‘count’ : 1
‘rank’ : 3
}
}
and so on ... etc
我正在使用下面的代码,但我需要输出我的一些j son格式,如同Excepted output下面你能帮我解决一下我是怎么做到的,或者让我知道我在这里做错了什么
答案 0 :(得分:1)
我认为这就是你想要的。我使用 $ frequency
创建了新数组$text = "A very nice únÌcÕdë text. Something nice to think Something about if you're into Unicode.";
$words = str_word_count($text, 1); // use this function if you only want ASCII
$frequency = array_count_values($words);
arsort($frequency);
$new_arr = array();
$rank_counter = 1;
foreach ($frequency as $key => $value) {
$new_arr[] = array(
'word' => $key,
'count' => $value,
'rank' => $rank_counter++,
)
}
$myJSON = json_encode($new_arr);
echo "<pre>";
print_r($myJSON);
输出
[
{
word: "nice",
count: 2,
rank: 1
},
{
word: "Something",
count: 2,
rank: 2
},
{
word: "A",
count: 1,
rank: 3
},
{
word: "very",
count: 1,
rank: 4
},
{
word: "n",
count: 1,
rank: 5
},
{
word: "c",
count: 1,
rank: 6
},
{
word: "d",
count: 1,
rank: 7
},
{
word: "text",
count: 1,
rank: 8
},
{
word: "to",
count: 1,
rank: 9
},
{
word: "think",
count: 1,
rank: 10
},
{
word: "about",
count: 1,
rank: 11
},
{
word: "if",
count: 1,
rank: 12
},
{
word: "you're",
count: 1,
rank: 13
},
{
word: "into",
count: 1,
rank: 14
},
{
word: "Unicode",
count: 1,
rank: 15
}
]