簡體   English   中英

循環遍歷關聯數組並賦值

[英]Loop through associative array and assign values

我有一個數組:

$instructions = array (
array("step_no"=>"1","description"=>"Ensure that you have sufficient balance"),
array("step_no"=>"2","description"=>"Approve the request sent to your phone")
);

我想要的是遍歷這個數組,我已經完成了,但我現在很困惑,因為我不知道如何獲得我想要的 output。

foreach ($array as $key => $value) { 
//echo $key . "\n"; 
foreach ($value as $sub_key => $sub_val) {      
    if (is_array($sub_val)) { 
        //echo $sub_key . " : \n"; 
        foreach ($sub_val as $k => $v) { 
            echo "\t" .$k . " = " . $v . "\n"; 
        } 
    } else { 
        echo $sub_key . " = " . $sub_val . "\n"; 
    } 
  } 
}

上面的代碼循環遍歷數組,但是這行代碼:

echo $sub_key . " = " . $sub_val . "\n";

給我:

step_no = 1 description = Ensure that you have sufficient balance step_no = 2 description = Approve the request sent to your phone

當我將其更改為:

echo $sub_val . "\n"; 

它給了我:

1 Ensure that you have sufficient balance 2 Approve the request sent to your phone

但我真正想要的是:

1. Ensure that you have sufficient balance 
2. Approve the request sent to your phone

這可能嗎? 謝謝。

聞起來好像您不是在命令行中而是在瀏覽器中運行此腳本。 如果是這樣,則\n不會產生視覺效果(除非在<pre>塊內)並且您必須使用 HTML 標簽<br />代替。 此外,放棄串聯瘋狂並使用變量替換:

echo "{$sub_key}. = {$sub_val}<br/>";
$instructions = array (
    array("step_no"=>"1","description"=>"Ensure that you have sufficient balance"),
    array("step_no"=>"2","description"=>"Approve the request sent to your phone")
);

foreach($instructions as $instruction) {
    echo $instruction['step_no'] . '. ' . $instruction['description'] . "\n";
}

如果是 HTML 您可能需要使用<ol><li>

您可以通過這種方式簡單地實現

<?php
    $instructions = array (
                           array("step_no"=>"1","description"=>"Ensure that you have sufficient balance"),
                           array("step_no"=>"2","description"=>"Approve the request sent to your phone")
);

   foreach($instructions as $instruction){

       echo $instruction['step_no'].'. '.$instruction['description'].PHP_EOL;
   }
?>

始終保持簡單。

暫無
暫無

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

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