计算 Json 中匹配词的数量

Count the Number of match Word in Json

我怎么可能算出匹配字符串的单词...比如

中匹配“201”的单词

这是我的后端...

<?php
$con=mysqli_connect("localhost","root","","project");
function loadData()
{
    global $con;
    $listData="";
    $sql=mysqli_query($con,"SELECT fGuests,mGuests FROM reserved");
    while($row=mysqli_fetch_array($sql))
    {
        $mf= array();
        $mf[]=$row['mGuests'].';'.$row['fGuests'];
        $data = array(
                    'mf'=>$mf
                    );
        $listData[]=$data;
    }
    return json_encode($listData);
}
echo loadData();

?> 这是我的 AJAX...

function x()
{
    $.ajax({
        url:"ajax/try.php",
        type:"GET",
        dataType:"JSON",
        data:"",
        success:function(data)
        {
            $.each(data,function(i,item)
            {
                var m=item.match(/201/g).length;
                $("#roomList2").append(m);
            });
        }
    });
}
x();

它只输出 6...

应该是 8...

我认为您只是在追加之前读取数组中的第一个对象(每个循环遍历而不是返回所有串联的结果)。这可能是因为当匹配 returns null 数组的第二个元素时出现错误(那个元素中没有 201)。需要添加一个 if 来检查是否匹配 returns 任何东西。您还想在追加之前将这些数字相加。

function x()
{
    $.ajax({
        url:"ajax/try.php",
        type:"GET",
        dataType:"JSON",
        data:"",
        success:function(data)
        {
            var m = 0;
            $.each(data,function(i,item)
            {
                var matched = item.mf.match(/201/g);
                if(matched) {
                    m += matched.length;
                }
            });
            $("#roomList2").append(m);
        }
    });
}
x();

jsfiddle of this working

如何将 data(对象)转换为字符串然后只搜索一次:

var strData = JSON.stringify( data );
var matched = strData.match(/201/g);
var m = matched ? matched.length : 0;

var data = [
 {mf:["tuper-201;tuper-201;tuper-201;tuper-201"]},
 {mf:["tuper-201;tuper-201;tuper-201;tuper-201"]},
 {mf:["tuper-201;tuper-201;tuper-201;tuper-201"]},
 {mf:["4-000;5-000;6-000;1-000;2-000;3-000"]},
 {mf:["4-000;5-000;6-000;1-000;2-000;3-000"]}
];
var strData = JSON.stringify( data );
var matched = strData.match(/201/g);
var m = matched ? matched.length : 0;
alert( m );