获取数组并循环

时间:2018-08-24 09:27:06

标签: php mysql

db中的目标值:

["html", "css", "xml", "json"]

php

$sql = "select tabs from t1 where db = 'link' limit 1";
$st = $db->prepare($sql);
$st->execute();
$arr = $st->fetch();
$tabs = "";
foreach ($arr as $el) {
    $tabs .= "<div class='tableft'>" . $el . "</div>\n";
}
echo $tabs;

结果:

<div class='tableft'>["html", "css", "xml", "json"]</div>
<div class='tableft'>["html", "css", "xml", "json"]</div>

我需要什么:

<div class='tableft'>html</div>
<div class='tableft'>css</div>
<div class='tableft'>xml</div>
<div class='tableft'>json</div>

1 个答案:

答案 0 :(得分:0)

您必须将json数据解析为数组并像这样在循环内遍历。

$sql = "select tabs from t1 where db = 'link' limit 1";
$st = $db->prepare($sql);
$st->execute();
$arr = $st->fetch();
$tabs = "";
foreach ($arr as $el) {
    $results = json_decode($el);
    foreach($results as $result) {
       $tabs .= "<div class='tableft'>" . $result . "</div>\n";
    }
}
echo $tabs;