0

我在通过 Codeigniter/MySQL 从图像数组中提取值时遇到问题。所以我的数据库中有一个名为“image”的表,如果我回显它,我会得到以下代码:

{"f01efdf6fe3b2bb387d3094aa701203f":{"filename":"f01efdf6fe3b2bb387d3094aa701203f.jpg","alt":"","caption":"","primary":true},"b11581adadd1848acb2898e7a284afc1":{"filename":"b11581adadd1848acb2898e7a284afc1.png","alt":"","caption":""},"2cfee6d3c334696833b1cfe13910fcf1":{"filename":"2cfee6d3c334696833b1cfe13910fcf1.png","alt":"","caption":""}}

如您所见,那里有3张图像,我需要的是在foreach循环中仅回显“主”值为:true的图像...

编辑:

<?php
$query = $this->db->query("SELECT * FROM offers_products WHERE offer_large LIMIT 5;");
?>

<?php foreach ($query->result() as $row): ?>

<li><a href="/<?=$row->slug?>"><?=$row->id?></a></li>
<li><?=$row->name?></li>
<li><!-- THIS IS THE IMAGES TABLE VALUE --> <?=$row->images?> <!-- --></li>
<li><?=$row->description?></li>

<?php endforeach; ?>
4

2 回答 2

1

您必须首先解码 json 编码字符串并从那里提取主图像:

这是您可以用来提取主图像的小函数:(如果您使用 CodeIgniter,可以将此函数放在 Helper 中)

function get_primary_image($encode_json_data)
{
    $primary_image = '';
    $decoded_json = json_decode($encode_json_data);
    foreach($decoded_json as $obj)
    {
        if(isset($obj->primary) && $obj->primary == 1)
            $primary_image = $obj->filename;
    }
    return $primary_image;
}

您可以通过以下方式在视图中调用上述函数:

<?php foreach ($query->result() as $row): ?>

<li><a href="/<?=$row->slug?>"><?=$row->id?></a></li>
<li><?=$row->name?></li>
<li> <?=get_primary_image($row->images)?></li><!-- Here, you call above function -->
<li><?=$row->description?></li>

<?php endforeach; ?>
于 2013-05-14T09:46:27.580 回答
1

也许:

$array = json_decode($stringFromDatabase, true);
$primary = false;
foreach ($array as $longStringDontCare => $imageArray) {
    if (!empty($imageArray['primary'])) {
       $primary = $imageArray;
       break;
    }
} 
if ($primary) {
   echo $primary['filename'];// should give: f01efdf6fe3b2bb387d3094aa701203f.jpg
}

给你最后一个提示:

<?php
function getPrimaryImageFromJsonString($stringFromDatabase) {
    $array = json_decode($stringFromDatabase, true);
    $primary = false;
    foreach ($array as $longStringDontCare => $imageArray) {
        if (!empty($imageArray['primary'])) {
           $primary = $imageArray;
           break;
        }
    } 
    if ($primary) {
       return $primary['filename'];
    }
    return null;
}
?>


<?php foreach ($query->result() as $row): ?>

<li><a href="/<?=$row->slug?>"><?=$row->id?></a></li>
<li><?=$row->name?></li>
<li><?php echo getPrimaryImageFromJsonString($row->images);?></li>
<li><?=$row->description?></li>

<?php endforeach; ?>

LE:一些编辑。

于 2013-05-14T09:07:06.213 回答