如果我有一个具有以下结构的数组,我需要确定最多使用哪个描述。
因此,在这种情况下,您可以看到在第一和第四组中使用了猫科动物,因此描述 - >猫科动物将是最常用的答案。如何在PHP中编写脚本以输出答案?
所以,如果我有一个名为$ stuff的数组:
Array (
[1] => Array (
[Title] => Cat
[Description] => Feline
[Age] => 7
)
[2] => Array (
[Title] => Dog
[Description] => Canine
[Age] => 8
)
[3] =>
Array (
[Title] => Birdie
[Description] => Winged Beast of the Air
[Age] => Eternal
)
[4] =>
(
[Title] => Kitten
[Description] => Feline
[Age] => 1
)
)
我找到了这段代码:
$c = array_count_values($stuff);
$val = array_search(max($c), $c);
但这不起作用,因为我只需要计算Description字段,而不是所有字段。那么,我该如何进入并缩小范围或将其收紧,以便我只计算并获得匹配描述的数量。
我的想法是尝试:
$c = array_count_values($stuff['Description']);
$val = array_search(max($c), $c);
但那没用。我错过了别的什么吗?
答案 0 :(得分:1)
请检查以下内容: -
<?php
$stuff = Array (
'1' => Array (
'Title' => 'Cat',
'Description' => 'Feline',
'Age' => 7
),
'2' => Array (
'Title' => 'Dog',
'Description' => 'Caine',
'Age' => 8
),
'3' => Array (
'Title' => 'Birdie',
'Description' => 'Winged Beast of the Air',
'Age' => 'Eternal'
),
'4' => Array (
'Title' => 'Kitten',
'Description' => 'Feline',
'Age' => 1,
)
);
$description_count = array();
foreach ($stuff as $key=>$value) {
// check and add to the description_count array
if (isset($description_count[$value['Description']])) {
$description_count[$value['Description']]++;
}
// if not exist then initialize 1
else $description_count[$value['Description']] = 1;
//in single line you can do it
$description_count[$value['Description']] = isset($description_count[$value['Description']]) ? $description_count[$value['Description']]++ : 1;
}
echo "<pre/>";print_r($description_count);
输出: - https://eval.in/388305