我将调查结果存储在mysql数据库中 我尝试输出结果很好,但现在我尝试以降序(最高的第一个)和正确的名称得到结果。现在输出是这样的:
print "<pre>";
print_r(array_count_values($array_a));
print "</pre>";
//OUTPUTS first key is the poll option and second is how much it was voted for.
[4] => 1
[12] => 17
[2] => 3
[6] => 42
[8] => 6
[16] => 5
[3] => 30
[18] => 1
[1] => 5
首先,我想用名字替换数字。这是我被卡住的地方。 str_replace不起作用,因为它替换所有匹配但不是确切数字的数字。 foreach循环正确,但有17个数字要替换,所以我喜欢使用数组来获取它们,但不知道如何。
foreach($array_a as &$value){
if($value==1){
$value = "opt1";
}
}
$patterns = array();
$patterns[0] = '1';
$patterns[1] = '2';
$patterns[2] = '3';
$patterns[3] = '4';
$replacements = array();
$replacements[0] = 'Car';
$replacements[1] = 'Boat';
$replacements[2] = 'Bike';
$replacements[3] = 'Photo';
我想要达到的结果:
//OUTPUT
[Car] => 30
[Bike] => 25
[Paint] => 10
[Goat] => 5
[Photo] => 3
答案 0 :(得分:0)
怎么样:
$replacements = array();
$replacements[2] = 'Car'; // your key should be the key of $array_a here and
$replacements[1] = 'Boat'; // value should be the key you want to be used
$replacements[5] = 'Bike';
$replacements[3] = 'Photo';
$finalPollArray = array();
foreach($replacements as $key => $value)
{
$finalPollArray[$value] = $array_a[$key];
}
$finalPollArray = asort($finalPollArray)
print "<pre>";
print_r($finalPollArray);
print "</pre>";
一个非常实际的例子是:
$poll[5] = 13;
$poll[6] = 12;
$poll[3] = 10;
$poll[12] = 7;
$poll[8] = 6;
$poll[1] = 5;
$poll[7] = 5;
$poll[16] = 5;
$poll[13] = 4;
// with this code I get the following output
$replacements = array();
$replacements[5] = 'Car';
$finalPollArrayA = array();
foreach($replacements as $key => $value)
{
$finalPollArrayA[$value] = $poll[$key];
}
print "<pre>";
print_r($finalPollArrayA);
print "</pre>";
这就输出了我:
Array
(
[Car] => 13
)
是否符合预期?