如何使用关联数组显示此类数据:
array(20) {
[0]=>
array(7) {
["url"]=>
string(89) "URL Here"
["title"]=>
string(42) "Title Here"
["author_url"]=>
string(51) "Author Link Here"
["author"]=>
string(14) "Author"
["published"]=>
string(14) "Date"
["img_url"]=>
string(73) "Image Link Here"
["teaser"]=>
string(352) "Lorem Ipsum"
}
}
我知道使用foreach($string as $key=>value)
是第一步,但我想知道如何使用它来回显值,然后在html元素中提供它们,以便上面的数据显示内容:
URL:URL Here
TITLE: Title Here
AUTHOR_URL: Author Link Here
AUTHOR: Author
PUBLISHED: Date
TEASER: Lorem Ipsum
提前感谢您提出任何建议。
答案 0 :(得分:2)
这里有一个嵌套数组,你需要2个foreach:
foreach ($array as $values) {
foreach ($values as $key => $v) {
printf("%s: %s\n", $key, $v);
}
}
答案 1 :(得分:2)
将第二个foreach
嵌入第一个foreach
:
echo '<p>';
foreach($array as $value)
{
foreach($value as $innerKey => $innerValue)
{
echo strtoupper($innerKey).': '.$innerValue;
echo '<br/>';
}
}
echo '</p>';
答案 2 :(得分:0)
简单的解决方案,无法处理格式化:
print_r($string);
更灵活的解决方案,使用格式化递归函数:
function custom_print_r($expression, $indent = 1) {
$buffer = '';
$str_indent = str_pad('', $indent * 2, ' ');
$arr_format = "[\n%s\n" . str_pad('', ($indent - 1) * 2 , ' ') . "]";
$row_format = "$str_indent%s => %s,\n";
$val_format = "%s";
if (is_array($expression)) {
$subbuffer = '';
foreach($expression as $key => $value) {
$subbuffer .= sprintf($row_format, $key, custom_print_r($value, $indent + 1));
}
$buffer .= sprintf($arr_format, $subbuffer);
} elseif (is_object($expression)) {
$subbuffer = '';
foreach(get_object_vars($expression) as $key => $value) {
$subbuffer .= sprintf($row_format, $key, custom_print_r($value, $indent + 1));
}
$buffer .= sprintf($arr_format, $subbuffer);
} else {
$buffer .= sprintf($val_format, $expression);
}
return $buffer;
}
$arr = [
[
"url" =>"URL Here",
"title" => "Title Here",
"author_url" => "Author Link Here",
"author" => "Author",
"published" => "Date",
"img_url" => "Image Link Here",
"teaser" => "Lorem Ipsum",
]
];
echo custom_print_r($arr);
/** Will produce :
[
0 => [
url => URL Here,
title => Title Here,
author_url => Author Link Here,
author => Author,
published => Date,
img_url => Image Link Here,
teaser => Lorem Ipsum,
],
]
**/