0

I need sort functions [function1(), function2(), function3()] in order of the values in array $numbers ($numbers[0], $numbers[1], $numbers[2]).

I only successfully sorted values $n1, $n2, $n3. But now I do not know how to sort functions below according these sorted values in array.

In this cause it means that first will be function3() next function1() and last function2(). And when I change values ($n1, $n2, $n3), order of functions will be automatically corrected.

$n1 = 50000;
$n2 = 100000;
$n3 = 25000;

$numbers = array($n1, $n2, $n3);
sort($numbers);

function function1() {
    global $n1; 
    echo 'STANDARD';
    echo '35 mil';
    echo number_format($n1, 0, '', ' ');
}
function function2() {
    global $n2;
    echo 'STANDARD PLUS';
    echo '70 mil';
    echo number_format($n2, 0, '', ' ');
}
function function3() {
    global $n3;
    echo 'STANDARD PLUS';
    echo '35 mil';
    echo number_format($n3, 0, '', ' ');
}

Thanks in advance (Sorry - I am very beginner in programming)

4

2 回答 2

1

How to change the order of the functions...

I'll answer the question in the topic first, because that's what I've been asked to do.

// First, create an array with the three values mapping to the three functions
$numbers = array(
    50000  => 'function1',
    25000  => 'function2',
    100000 => 'function3'
);
ksort($numbers);

// Next, define the functions
function function1($number) {
    echo "STANDARD<br>";
    echo "35 mil<br>";
    echo number_format($number, 0, '', ' ') . "<br>";
}
function function2($number) {
    echo "STANDARD PLUS<br>";
    echo "70 mil<br>";
    echo number_format($number, 0, '', ' ') . "<br>";
}
function function3($number) {
    echo "STANDARD PLUS<br>";
    echo "35 mil<br>";
    echo number_format($number, 0, '', ' ') . "<br>";
}

// Finally, let's call the functions in order
foreach($numbers as $value => $function) {
    $function($value);
}

(Demo)

However, we can make this MUCH simpler...

Since these functions all basically follow the same pattern, they should really be one function, within the foreach loop structure. Therefore, I'd do this:

// Set up variable parameters within the array
$numbers = array(
    50000 => array(
        'tier' => 'STANDARD',
        'mil'  => '35 mil'
    ),
    25000 => array(
        'tier' => 'STANDARD PLUS',
        'mil'  => '70 mil'
    ),
    100000 => array(
        'tier' => 'STANDARD PLUS',
        'mil'  => '35 mil'
    )
);

// Sort the array
ksort($numbers);

// Now, run the logic
foreach($numbers as $number => $details) {
    echo $details['tier'] . "<br>";
    echo $details['mil'] . "<br>";
    echo number_format($number, 0, '', ' ') . "<br>";
}

(Demo)

As you can see, it's a lot shorter and doesn't require expensive function calls.

于 2013-08-08T20:35:19.053 回答
0

“排序功能”是什么意思?是否要更改调用函数的顺序?

我看到您没有从代码中的任何地方调用您的函数。那么,你最初打算做什么?

于 2013-08-08T20:12:49.010 回答