簡體   English   中英

備用線條顏色-了解提供的代碼

[英]Alternate line colors - understanding a code provided

在這樣的例子中

$c = true; // Let's not forget to initialize our variables, shall we?
foreach($posts as $post)
    echo '<div'.(($c = !$c)?' class="odd"':'').">$post</div>";

我想了解這是如何工作的。

在這個例子中我們要做什么? 是否通過將true更改為false並將false更改為true來替換div行?

是。

$c = !$c為其本身分配相反的$c值。 然后分配后評估變量。

這導致在truefalse之間不斷變化的值。

此代碼利用了foreach循環。 如果您有普通的for循環,則可以改用counter變量:

for($i = 0, $l = count($posts); $i < $l; $i++) {
    echo '<div'.(($i % 2)?' class="odd"':'').">{$posts[$i]}</div>";
}

如果您為變量分配了有意義的名稱,並且對空格很慷慨,那么代碼通常更容易理解:

<?php

$odd = true;
foreach($posts as $post){
    echo '<div' . ( $odd ? ' class="odd"' : '' ) . ">$post</div>";
    $odd = !$odd;
}

在很短的空間里發生了很多騙術。 您可以將循環的內部分為三行:

$c = !$c; // invert c
$class_part = $c ? ' class="odd"':''; // if c is true, class is odd.
echo "<div$class_part>$post</div>"; // print the <div> with or without the class
                                    // depending on the iteration

是。

$c = true;
$not_c = !$c; // $not_c is now false
$c = !$c;     // same as above, but assigning the result to $c. So $c is now false
$c = !$c;     // $c is now true again

您提供的代碼段可以這樣重寫(並且可以說得更清楚):

$c = true;
foreach ($posts as $post) {
    $c = !$c;
    echo '<div' . ($c ? ' class="odd"' : '') . ">$post</div>";
}

$c ? ... : ... $c ? ... : ...語法正在使用三元運算符。 這有點像if語句的簡寫。 例如, true ? "a" : "b" true ? "a" : "b"計算為“ a”。

PHP中的分配返回新分配的值。 所以$c = !$c$cfalse時返回true $ctrue$c false

當“?”之前的條件時, 三元運算符 (? :)會計算“:”之前的部分。 為true,否則為':'之后的部分。 因此,它在“:”之前或之后輸出文本。

正如其他人所說,最好以一種更易理解的方式編寫此代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM