开发者

Replace array keys (foreach loop) who matches another array

I've got poll results stored in a mysql database.

I try to output the results which go's well, but now I try to get the result in descending order (highest first) and with开发者_如何转开发 the right name. Now the output is like this:

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

First I like to replace the numbers with a name. This is where I got stuck. str_replace doesn't work cause it replaces all numbers matching but not the exact number. The foreach loops get it right but there a 17 numbers to be replaced so I like to use an array to get them from but don't know how.

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';

The result I like to achieve:

 //OUTPUT
[Car] => 30
[Bike] => 25
[Paint] => 10
[Goat] => 5
[Photo] => 3


How about:

$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>";

A very practical example would be:

$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>";

and this outputs me:

Array
(
    [Car] => 13
)

is it as expected?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜