2013-11-24 51 views
0

我在db中有12個圖像鏈接,我可以用get_field('opt3_img_N')調用,其中N可以是1-12中的任何數字。 (我爲任何熟悉的人使用wordpress)。PHP中更高效的算法

我遇到的麻煩是想出一種有效的方式來按照我想要的方式輸出圖像。

我需要將鏈接平均分配到3個div。理想情況下,我想要圖像1在div 1中,圖像2在div 2中,圖像3在div 3中,圖像4在div 1中等。

但是,我不能爲了我的生活,弄清楚。我知道這可能是以很多方式完成的,但我在網上找不到任何東西。

我有現在的問題是:

<div class="div-1"> 
<?php for($i = 1; $i <= 4; $i++) { 
    $img = get_field("opt3_img_$i") ?: get_template_directory_uri() . "/images/default.jpg"; 
    $url = get_field("opt3_url_$i") ?: "#"; ?> 
    <a href="<?php echo $url ?>"><img src="<?php echo $img ?>" /></a> 
<?php endfor ?> 
</div> 

等與div的2和3本質上,它是那種做它的蠻力方式。這是現在它,但我想知道是否有更好的方法來做到這一點。

PS。我不確定這是否是一個很好的問題,所以請在需要時投票表決。

謝謝。

回答

1

有一些構建HTML的方式。打印前Thisn一個構建塊DIV ...

$myDivs = array(); 
$divNo = 4; // set to the number of div blocks you want to split between 
$imgCount = 12; // set to number of images. 

for($i = 1; $i <= $imgCount; $i++) { 
    $img = get_field("opt3_img_$i") ?: get_template_directory_uri() . "/images/default.jpg"; 
    $url = get_field("opt3_url_$i") ?: "#"; 
    // use modulo operator to decide which div to print in.... 
    $idx = ($i - 1) % ($divNo-1); 
    // I like heredocs... 
    $myDivs[ $idx][] = <<<EOF 
<a href="$url"><img src="{$img}" /></a> 
EOF; 
} 
// print the divs one after the other.... 
$j = 1; 
foreach ($myDivs as $div) { 
    $text = join("\n", $div); 
    echo "<div class='div-{$j}'>{$text}</div>\n"; 
    $j++; 
} 
+0

我建立像這樣在第一,但發現我現在的解決方案更具可讀性。我想,我希望能縮短一些東西。但我會將其標記爲答案,因爲它完全符合我的需要。 – clueless

+0

謝謝:-)但你的問題的解決方案不會按照你的要求拆分圖像 - 它應該把1,4,7,10放在div 1中,而你只需放1,2,3,4 – vogomatix

0

有很多方法可以做到這一點,我不確定蠻力是什麼意思,但這不是蠻力,它只是一個循環。

你在這裏有一個循環的正確軌道,你需要開始考慮的是遊標。

//PSEUDO CODE 
$div_pointer = 1; 
for($i = 0; $i < 12; $i++) { 
    <div class=$div_pointer> 
    $div_pointer++; 
    if($div_pointer > 3) $div_pointer = 1; 
} 

這基本上是一個使用變量來跟蹤要將圖像寫入哪個div的僞示例。 $i變量正在迭代主數據集,而光標正在跟蹤要寫入的3個div中的哪一個。一旦它到達第四fiv它重置回來。可以幫助我們以一種新的方式來看問題。

話雖這麼說,有更好的方法來獲得圖像轉換成div的:P

0

你可以做一次:

<?php 
    $dir=get_template_directory_uri(); // Get template dir 
    for($i=1;$i < 4;++$i){ 
    echo '<div class="div-'.$i.'">'; 
    $img = get_field("opt3_img_$i") ? : $dir . "/images/default.jpg"; 
    $url = get_field("opt3_url_$i") ? : "#"; 
    echo '<a href="'.$url.'"><img src="'.$img.'" /></a>'; 
    echo'</div>'; 
    } 
?> 

快樂編碼