doujia1988
2012-12-10 16:46 阅读 30
已采纳

按顺序打印数组值和变量

I am sure there is a simpler solution to this that I am over looking

Here is some code that basically describes what I am doing:

$array = array('1.4','2.7','4.1','5.9'); 
$score = '4.4';
foreach($array as $value) {
    if($score>$value){
        $x = $value;
    }
}
foreach($array as $value) {
    if($x==$value){
        echo $value."<br>";
        echo $score."<-- <br>";
    } else {
        echo $value."<br>";
    }
}

Will display as:

1.4
2.7
4.1
4.4<--
5.9

What I am trying to do is print the array values with the score value in order.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

2条回答 默认 最新

  • 已采纳
    douxin2002 douxin2002 2012-12-10 16:50

    Why don't you change the array to actual numerical values and then sort it?

    $array = array(1.4, 2.7, 4.1, 5.9);
    $score = 4.4;
    
    $array[] = $score;
    sort($array);
    

    Or if you need to work with strings:

    $array = array('1.4', '2.7', '4.1', '5.9');
    $score = '4.4';
    $array[] = $score;
    sort($array, SORT_NUMERIC);
    
    点赞 评论 复制链接分享
  • duanquyong8164 duanquyong8164 2012-12-10 16:55

    For sorting, what might be the easiest is to use the sort() method (docs).

    You're overwriting $x each time through your first loop. ... the way it's written, when you're done with the first loop, $x has the last value that's less than $score. (Are you identifying a cut-off line?)

    After you've sorted with the sort() method, your second loop should work as you intend. There are tighter ways to do the printing (for example, you can implode()), but what you've got should work.

    点赞 评论 复制链接分享

相关推荐