从Codeigniter中的Array中提取图像值

时间:2013-05-14 08:59:08

标签: php mysql

我遇到了通过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循环中为真...

编辑:

<?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; ?>

2 个答案:

答案 0 :(得分: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; ?>

L.E:一些编辑。

答案 1 :(得分: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; ?>