1

コンマ、スペース、または句読点で区切られた項目をリストする必要があることがよくあります。住所は典型的な例です (これは住所としてはやり過ぎであり、例を示すためのものです!):

echo "L$level, $unit/$num $street, $suburb, $state $postcode, $country.";
//ouput: L2, 1/123 Cool St, Funky Town, ABC 2000, Australia.

簡単に聞こえるかもしれませんが、変数が存在する場合にのみ、変数間にカスタム セパレータを「条件付きで」追加する簡単な方法はありますか? 各変数が設定されているかどうかを確認する必要がありますか? したがって、上記を使用すると、詳細度の低い別の住所が次のように出力される場合があります。

//L, / Cool St, , ABC , .

少し面倒なチェック方法は、各変数が設定されているかどうかを確認し、句読点を表示することです。

if($level){ echo "L$level, "; }
if($unit){ echo "$unit"; }
if($unit && $street){ echo "/"; }
if($street){ echo "$street, "; }
if($suburb){ echo "$suburb, "; }
//etc...

すべてのストリッピング/フォーマットなどを自動的に実行できる関数があるとよいでしょう。

somefunction("$unit/$num $street, $suburb, $state $postcode, $country.");

もう 1 つの例は、単純な csv リストです。コンマで区切られた x 個のアイテムを出力したい:

for($i=0; $i=<5; $i++;){ echo "$i,"; }
//output: 1,2,3,4,5,

たとえば、ループでは、配列の最後の項目を決定する最良の方法、またはリストの最後にコンマを含めないようにループ条件が満たされていることを確認するにはどうすればよいでしょうか? 私が読んだこれを回避する1つの長い方法は、次のような最初のエントリを除いて、アイテムの前にコンマを置くことです:

$firstItem = true; //first item shouldn't have comma
for($i=0; $i=<5; $i++;){
  if(!$firstItem){ echo ","; }
  echo "$i";
  $firstItem = false;
}
4

8 に答える 8

1

Phillip の回答はあなたの質問に対応していますが、 Eric Lippertによる次のブログ投稿で補足したいと思います。彼の議論は c# に関するものですが、どのプログラミング言語にも当てはまります。

于 2009-04-15T13:56:33.090 に答える
1

わかりました、それを取ってください!(でも大げさではないです^^)

<?php

function bothOrSingle($left, $infix, $right) {
    return $left && $right ? $left . $infix . $right : ($left ? $left : ($right ? $right : null));
}

function leftOrNull($left, $postfix) {
    return $left ? $left . $postfix : null;
}

function rightOrNull($prefix, $right) {
    return $right ? $prefix . $right : null; 
}

function joinargs() {
    $args = func_get_args();
    foreach ($args as $key => $arg) 
        if (!trim($arg)) 
            unset($args[$key]);

    $sep = array_shift($args);
    return join($sep, $args);
}

$level    = 2;
$unit     = 1;
$num      = 123;
$street   = 'Cool St';
$suburb   = 'Funky Town';
$state    = 'ABC';
$postcode = 2000;
$country  = 'Australia';

echo "\n" . '"' . joinargs(', ', rightOrNull('L', $level), bothOrSingle(bothOrSingle($unit, '/', $num), ' ', $street), bothOrSingle($state, ' ', $postcode), bothOrSingle($country, '', '.')) . '"';

// -> "L2, 1/123 Cool St, ABC 2000, Australia."

$level    = '';
$unit     = '';
$num      = '';
$street   = 'Cool St';
$suburb   = '';
$state    = 'ABC';
$postcode = '';
$country  = '';

echo "\n" . '"' . joinargs(
    ', ', 
    leftOrNull(
        joinargs(', ', 
            rightOrNull('L', $level), 
            bothOrSingle(bothOrSingle($unit, '/', $num), ' ', $street), 
            bothOrSingle($state, ' ', $postcode), 
            $country
        ),
        '.'
    )
) . '"';

// -> "Cool St, ABC."


$level    = '';
$unit     = '';
$num      = '';
$street   = '';
$suburb   = '';
$state    = '';
$postcode = '';
$country  = '';

echo "\n" . '"' . joinargs(
    ', ', 
    leftOrNull(
        joinargs(', ', 
            rightOrNull('L', $level), 
            bothOrSingle(bothOrSingle($unit, '/', $num), ' ', $street), 
            bothOrSingle($state, ' ', $postcode), 
            $country
        ),
        '.'
    )
) . '"';

// -> "" (even without the dot!)

?>

はい、わかっています。

于 2009-04-15T17:03:22.673 に答える
0
<?php
    $level  = 'foo';
    $street = 'bar';
    $num    = 'num';
    $unit   = '';

    // #1: unreadable and unelegant, with arrays
    $values   = array();
    $values[] = $level ? 'L' . $level : null;
    // not very readable ...
    $values[] = $unit && $num ? $unit . '/' . $num : ($unit ? $unit : ($num ? $num : null));
    $values[] = $street ? $street : null;

    echo join(',',  $values);


    // #2: or, even more unreadable and unelegant, with string concenation
    echo trim( 
        ($level ? 'L' . $level . ', ' : '') . 
        ($unit && $num ? $unit . '/' . $num . ', ' : ($unit ? $unit . ', ' : ($num ? $num . ', ': '')) .
        ($street ? $street . ', ': '')), ' ,');

    // #3: hey, i didn't even know that worked (roughly the same as #1):
    echo join(', ', array(
        $level ? 'L' . $level : null,
        $unit && $num ? $unit . '/' . $num : ($unit ? $unit : ($num ? $num : null)),
        $street ? $street : null
    ));
?>
于 2009-04-15T15:03:45.317 に答える
0

言語の配列メソッドを使用する方が高速で簡単であることが常にわかります。たとえば、PHP では次のようになります。

<?php
echo join(',', array('L'.$level, $unit.'/'.$num, 
          $street, $suburb, $state, $postcode, $country));
于 2009-04-15T13:52:19.323 に答える