如何为不同变量重复相同的操作

时间:2017-08-31 09:14:26

标签: php arrays

<!-- language: php -->       
<?php
 // test variables
    $l1 = "http://youtube.com/channel/";
    $l2 = "http://youtube.com/channel/";
    $l3 = "http://youtube.com/channel/";
    $l4 = "http://youtube.com/channel/";
    $fl = "http://youtube.com/channel/";

    //set error false as default
    $error = "false";

    //check if variables are ready for use, if they are, add them to `$l` array
    //I do each check as a seperate line, as it looks cleaner than 1 long if statement.
$l = [];
if(!empty($l1)) $l[] = $l1;
if(!empty($l2)) $l[] = $l2;
if(!empty($l3)) $l[] = $l3;
if(!empty($l4)) $l[] = $l4;
if(!empty($fl)) $l[] = $fl;

foreach($l as $key => $value) {

    //1 line ternary is cleaner than if/else statetmnt
    $errorKey = $key < 9? "0{$key}" : $key;

    //each row by default has no error
    $hasError = 0;

    //check if this a valid url 
    if(!preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $value)) {
        $error = "true";
        $hasError = 1;
    }

    if($hasError) {
        //store error in array, to loop through later
        $errors[] = $errorKey;
    }
}
$search = '?sub_confirmation=1';
$searchUrl = "youtube.com/channel";

if (strpos($l, $searchUrl) !== false && strpos($l, $search) === false) {
    $l =  $value."".$search;
}

if($error == "false") {
    echo $l1;
    echo $l2;
    echo $l3;
    echo $l4;
    echo $fl;
}

// deliver the error message
//Check if $error has been set to true at any point
if($error == "true") {
    //loop through error array, echo error message if $errorNumber matches.
    //at this point we KNOW there was an error at some point, no need to use a switch really
    foreach($errors as $errorNumber) {
        echo "Something went wrong here $errorNumber :o";
    }
}
?>

您好,我的问题是在strpos函数所在的代码的末尾,所以基本上我想检查每个url,如果它包含某个url,则返回一次,如果是这样的话,则添加一些内容。但是我不想重复4次if语句($ fl变量不必检查),我很新,所以我希望有人可以帮助我,我想要一个开关声明,但我想有更好的方法。如果我把它放在foreach aboth中,它就不适用于某些变量,只适用于值变量。

2 个答案:

答案 0 :(得分:0)

您可以使用此foreach标头通过引用分配$value(请注意&前面的$value):

foreach($l as $key => &$value) {

通过这样做,您对$value所做的每项更改也将对$l数组中的相应值进行。

然后在foreach循环的末尾你输入这段代码:

if (strpos($value, $searchUrl) !== false && strpos($value, $search) === false) {
    $value .= $search;
}

所以你的最终foreach循环应如下所示:

foreach($l as $key => &$value) {

    //1 line ternary is cleaner than if/else statetmnt
    $errorKey = $key < 9? "0{$key}" : $key;

    //each row by default has no error
    $hasError = 0;

    //check if this a valid url 
    if(!preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $value)) {
        $error = "true";
        $hasError = 1;
    }

    if($hasError) {
        //store error in array, to loop through later
        $errors[] = $errorKey;
    }

    $search = '?sub_confirmation=1';
    $searchUrl = "youtube.com/channel";
    if (strpos($value, $searchUrl) !== false && strpos($value, $search) === false) {
        $value .= $search;
    }
}

您可以在此处阅读有关在foreach循环中使用引用的更多信息:PHP: foreach

修改 要将更改不仅应用于$l数组的元素,还应用于原始变量$l1$l2等,您还应将元素分配给数组作为参考:

$l = [];
if(!empty($l1)) $l[] = &$l1;
if(!empty($l2)) $l[] = &$l2;
if(!empty($l3)) $l[] = &$l3;
if(!empty($l4)) $l[] = &$l4;
if(!empty($fl)) $l[] = &$fl;

答案 1 :(得分:0)

就我个人而言,我认为这是转移到class的良好候选人。说实话,我不是100%确定你在做什么,但会尝试将你的代码转换成一个类。

class L {
    public $raw = null;
    public $modified = null;
    public $error = false;
    // create the class
    public function __construct($data=null) {
        $this->raw = $data;
        // Check the raw passed in data
        if ($data) {
            $this->isUrl();
        }
        // If there was no error, check the data
        if (! $this->error) {
            $this->search();
        }
    }
    // Do something ?
    public function debug() {
         echo '<pre>';
         var_dump($this);
         echo '</pre>';
    }
    public function getData() {
        return ($this->modified) ? : $this->raw;
    }
    private function isUrl() {
        $this->error = (! preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $this->raw)); 
    }
    // Should a failed search also be an error?
    private function search() {
        if ($this->raw) {
            if ( (strpos($this->raw, "youtube.com/channel") !== false) &&
                 (strpos($this->raw, "?sub_confirmation=1") === false) ) {
                $this->modified = $this->raw ."?sub_confirmation=1";
            }
        }
    }
}

// Test data
$testList[] = "test fail";
$testList[] = "https://youtube.com/searchFail";
$testList[] = "https://youtube.com/channel/success";
$testList[] = "https://youtube.com/channel/confirmed?sub_confirmation=1";

// Testing code
foreach($testList as $key=>$val) {
    $l[] = new L($val);   
}

foreach($l as $key=>$val) {
    // Check for an error
    if ($val->error) {
        $val->debug();
    } else {
        echo '<pre>'.$val->getData().'</pre>';
    }
}

输出结果为:

object(L)#1 (3) {
  ["raw"]=>
  string(9) "test fail"
  ["modified"]=>
  NULL
  ["error"]=>
  bool(true)
}

https://youtube.com/searchFail
https://youtube.com/channel/success?sub_confirmation=1
https://youtube.com/channel/confirmed?sub_confirmation=1