从 json 中找出最常见的元素
Find most common element from json
在我的 Twig 文件中,我循环遍历 JSON 文件中的数组。例如
r.dep[1].iata_code: "FRA"
r.dep[2].iata_code: "AMS"
r.dep[3].iata_code: "AMS"
r.dep[3].iata_code: "DBM"
如何找到最常见的值(在本例中为 AMS)并将其设置在变量中?
首先解析传入的json。比构建一个新数组并对该数组排序。
试试这个:
$r = json_decode($jsonstring); // parse your json string
$items = []; // define empty array
// Loop through the parsed JSON, counting occurrences
foreach($r->dep as $dep) {
if (array_key_exists($dep->iata_code, $items) {
$items[$dep->iata_code]++;
} else {
$items[$dep->iata_code] = 1;
}
}
// Now reverse sort the array
arsort($items);
// Max item is now the first one:
$max = array_keys($items)[0]; // AMS
在我的 Twig 文件中,我循环遍历 JSON 文件中的数组。例如
r.dep[1].iata_code: "FRA"
r.dep[2].iata_code: "AMS"
r.dep[3].iata_code: "AMS"
r.dep[3].iata_code: "DBM"
如何找到最常见的值(在本例中为 AMS)并将其设置在变量中?
首先解析传入的json。比构建一个新数组并对该数组排序。
试试这个:
$r = json_decode($jsonstring); // parse your json string
$items = []; // define empty array
// Loop through the parsed JSON, counting occurrences
foreach($r->dep as $dep) {
if (array_key_exists($dep->iata_code, $items) {
$items[$dep->iata_code]++;
} else {
$items[$dep->iata_code] = 1;
}
}
// Now reverse sort the array
arsort($items);
// Max item is now the first one:
$max = array_keys($items)[0]; // AMS