我有一个如下所示的数组(我做了一个json_encode,因此它在StackOverflow上更容易阅读)。我试图根据颜色数量获得最高的颜色数。因此,例如像Red这样的单色有32的计数而White有31的数量。那么我想得到32的最高值。对于双色我想要回来因为[白色,黑色]在双色中具有最高计数。对于三色我想要回到8,因为它们都是平等的等等。
[{
"colors" : "",
"count" : 55
}, {
"colors" : "[\"Red\"]",
"count" : 32
}, {
"colors" : "[\"Green\"]",
"count" : 32
}, {
"colors" : "[\"Blue\"]",
"count" : 32
}, {
"colors" : "[\"White\"]",
"count" : 31
}, {
"colors" : "[\"Black\"]",
"count" : 31
}, {
"colors" : "[\"White\",\"Black\",\"Red\"]",
"count" : 8
}, {
"colors" : "[\"Blue\",\"Red\",\"Green\"]",
"count" : 8
}, {
"colors" : "[\"White\",\"Blue\",\"Red\"]",
"count" : 8
}, {
"colors" : "[\"Blue\",\"Black\",\"Green\"]",
"count" : 8
}, {
"colors" : "[\"White\",\"Black\",\"Green\"]",
"count" : 8
}, {
"colors" : "[\"White\",\"Black\"]",
"count" : 4
}, {
"colors" : "[\"Black\",\"Green\"]",
"count" : 3
}, {
"colors" : "[\"White\",\"Red\"]",
"count" : 3
}, {
"colors" : "[\"Blue\",\"Green\"]",
"count" : 3
}, {
"colors" : "[\"Blue\",\"Red\"]",
"count" : 3
}
]
我想在数组中检索这些值。结果如下:
$max_color_count = array(55, 32, 4, 8);
55来自0颜色,32来自单色,4来自双色,8来自三色。
答案 0 :(得分:0)
这适用于数组。
$max_color_count = array(0, 0, 0, 0);
foreach($data as $k => $v)
{
$colors_amount = count($v['colors']);
$max_color_count[$colors_amount] = max($max_color_count[$colors_amount], $v['count']);
}
print_r($max_color_count);
这适用于$data = json_decode("JSON_YOU_HAVE_GIVEN");
$max_color_count = array(0, 0, 0, 0);
foreach($data as $k => $v)
{
$colors_amount = count(json_decode($v->colors));
$max_color_count[$colors_amount] = max($max_color_count[$colors_amount], $v->count);
}
print_r($max_color_count);