簡體   English   中英

帶 Word 的數組值,例如二 - 2、三 - 3

[英]Array values with Word for e.g. Two - 2, Three - 3

這是我使用的數組

$a = array("1"=>2,"2"=>8,"3"=>9,"4"=>8,"5"=>6,"6"=>7,"7"=>9,"8"=>2);

我試圖讓 output 在 2 打印 2-2 時得到類似的東西,當 3 打印 3-3 時

//Desired Output
Two - 2
Eight -8
Nine - 9

我通過使用另一個數組得到了這個想要的 output

這段代碼使用 null 作為 array_map() function 中的回調創建 arrays 數組

$b = array("Two", "Eight", "Nine", "Eight", "Six", "Seven", "Nine", "Two");

$array = array_map(null, $a, $b);
    
    foreach($array as $value) {
        
        echo $value[1]."-".$value[0]."<br>";
}

所以,我想做的是在不使用另一個數組 $b 的情況下獲得所需的 OUTPUT 我不知道如何不使用另一個數組。 有可能與任何條件有關還是我在問愚蠢的問題? 我剛開始學習 php。

我試圖找到解決方案,但我沒有到達那里。 如果已經有解決方案,請參考我

// $a = array("1"=>2,"2"=>8,"3"=>9,"4"=>8,"5"=>6,"6"=>7,"7"=>9,"8"=>2); // used short array notation (see references) and removed keys (since not used)
$numbers = [2,8,9,8,6,7,9,2,95890814984141]; // the last number is for my pleasure :P
$numberFormatter = new NumberFormatter('en', NumberFormatter::SPELLOUT);

foreach ($numbers as $number) {
    $numberSpelled = $numberFormatter->format($number);
    $numberSpelledWithFirstCharUpper = ucfirst($numberSpelled);
    
    echo $numberSpelledWithFirstCharUpper . ' - ' . $number . PHP_EOL;
}

output

Two - 2
Eight - 8
Nine - 9
Eight - 8
Six - 6
Seven - 7
Nine - 9
Two - 2
Ninety-five trillion eight hundred ninety billion eight hundred fourteen million nine hundred eighty-four thousand one hundred forty-one - 95890814984141

工作示例

參考


專家提示

給你的變量起有意義的名字——讓代碼更容易閱讀和理解。

是的,您必須為此創建另一個數組或將值放在現有數組上,但如果您不為此使用array_map() ,這將是一種很好的做法。

foreach($a as $key=>$value) {
    
    echo $b[$key]."-".$value."<br>";

添加一個查找數組並:

$lookup = [
    'zero',
    'one',
    'two',
    'three',
    'four',
    // etc...
];
$a = array("1"=>2,"2"=>4,"3"=>1,"4"=>1,"5"=>2,"6"=>3,"7"=>3,"8"=>2);
foreach ($a as $num) {
    echo $lookup[$num] . '-' . $num;
}

在這里拉小提琴。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM