我有一个数组:
$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 ($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
这有可能吗?谢谢。
答案 0 :(得分:1)
闻起来好像您不是在命令行中运行此脚本,而是在浏览器中运行。如果是这样,则\n
不会产生视觉效果(除非在<pre>
块内),您必须使用HTML标签<br />
来代替。另外,删除级联疯狂并使用变量替换:
echo "{$sub_key}. = {$sub_val}<br/>";
答案 1 :(得分:1)
list
如果是HTML,则可能要使用$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";
}
和<ol>
。
答案 2 :(得分:1)
您可以通过这种方式简单实现
<?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;
}
?>
总是保持简单。