我正在用PHP编写一条闪存消息,但是我希望为我的每一条闪存消息都有一个特定的标题。我的闪存信息容器是在我的header.php中设置的,所以我可以在我的站点上的任何地方使用这个系统:
<?php if(isset($_SESSION["flash-message"])): ?>
<?php foreach($_SESSION["flash-message"] as $type => $message): ?>
<div class="alert alert-<?= $type; ?>">
<p><?= $message; ?></p>
</div>
<?php endforeach; ?>
<?php endif; ?>要执行它,我使用以下命令:
$_SESSION["flash-message"]["success"] = "Test";所以,我有:

现在,我想要一个头衔,你知道吗?就像这样:
$_SESSION["flash-message"]["title" = "The title"]["success"] = "The message"就像那样。我想要上面的标题。
发布于 2016-02-14 01:00:17
简短的回答:使用数组或对象来存储带有相应标题的消息。
$_SESSION["flash-message"]["success"] = array("Title", "The Message");您的代码如下所示:
<?php if(isset($_SESSION["flash-message"])): ?>
<?php foreach($_SESSION["flash-message"] as $type => $message): ?>
<div class="alert alert-<?= $type; ?>">
<h2><?= $message[0]; ?></h2>
<p><?= $message[1]; ?></p>
</div>
<?php endforeach; ?>
<?php endif; ?>编辑:如果你有一个以上的成功信息,会发生什么?当前代码不支持多个“相同类型”消息。它应该是:
$_SESSION["flash-message"]["success"][] = array("Title", "The Message"); 存储多条“相同类型”消息。
编辑-2:你也可以使用对象方法-更易读。还包含我前面提到的多条消息功能。
<?php
$message = new stdClass();
$message->title = "Title";
$message->message = "The Message";
$_SESSION["flash-message"]["success"][] = $message;
?>
<?php if(isset($_SESSION["flash-message"])): ?>
<?php foreach($_SESSION["flash-message"] as $type): ?>
<?php foreach ($type as $message): ?>
<div class="alert alert-<?= $type; ?>">
<h2><?= $message->title; ?></h2>
<p><?= $message->message; ?></p>
</div>
<?php endforeach; ?>
<?php endforeach; ?>
<?php endif; ?>发布于 2016-02-14 01:34:40
$_SESSION["flash-message"]应该是数组 of messages,message应该有event_type、标题和内容。
您可以使用类或关联数组以多种形式对消息进行建模。请参阅使用关联数组建模的此示例消息:
$a_message = [
"event_type" => "success",
"title" => "The title"
"content" => "The message"
];这样,您就可以像这样实现foreach循环:
<?php if(isset($_SESSION["flash-message"])): ?>
<?php foreach($_SESSION["flash-message"] as $message): ?>
<div class="alert alert-<?= $message["event_type"]; ?>">
<h1><?= $message["title"]; ?></p>
<p><?= $message["content"]; ?></p>
</div>
<?php endforeach; ?>
<?php endif; ?>https://stackoverflow.com/questions/35387181
复制相似问题