计算数据并分成两列

时间:2011-03-10 02:03:20

标签: php

我正在调整一个循环和回声数据的facebook专辑类。问题是当它回声时它循环到一列,我想把它分成2列。这就是现在的样子:

foreach($json->data as $v)
                    {
echo "<a class='ImageLink' rel='lightbox[photos]' href = '".$v->source."'><img style='margin:10px;' width='110px' src='".$v->picture."' /></a>";
                    }

我正在尝试这样做:

$count = count($json->data);
$half_count = $count/2;
             echo "<ul class='float:left;'>";
$counter = 0;
    foreach($json->data as $v)
                        {
        if ($counter == $half_count +1){echo "<ul class='float:left;'>";}
            echo "<li>". $v->picture  ."</li>";
        if ($counter == $half_count){ echo "</ul>";}

                        $counter++;
                        }
    echo "</ul>";

但是当我在$ json-&gt;数据上使用count函数并回显时,它给了我一个数组。请帮忙;

1 个答案:

答案 0 :(得分:3)

“但是当我在$ json-&gt;数据上使用count函数并回显时,它给了我一个数组。” &lt; - Count将始终返回int。

对您的代码进行以下更正:

$count = count($json->data);
$half_count = ceil($count / 2); // make sure to ceil to an int. This will have your first column 1 larger than the second column when the count is odd
echo '<ul style="float:left">';
$counter = 0;
foreach($json->data as $v) {
    echo '<li>' , $v->picture , '</li>';
    $counter += 1;
    if ($counter == $half_count && $count != 1) {
        echo '</ul><ul style="float:right">';
    }
}
echo "</ul>";