【问题标题】:Editing array's items Php编辑数组的项目 PHP
【发布时间】:2018-12-19 05:14:44
【问题描述】:

我正在尝试编辑数组的项目。我在下面有 $links 数组。

array(6) {
  [0]=>
  string(22) "http://sumiyoshi22.jp/"
  [1]=>
  string(27) "https://www.finecity138.jp/"
  [2]=>
  string(25) "http://www.hirakata-p.jp/"
  [3]=>
  string(24) "http://www.honki-pj.com/"
  [4]=>
  string(55) "http://nishitetsu-sumai.com/centermarkstower/index.html"
  [5]=>
  string(29) "http://senri100.jp/index.html"
}

并试图让它看起来像这样:

array(6) {
  [0]=>
  string(29) "http://sumiyoshi22.jp/outline"
  [1]=>
  string(39) "https://www.finecity138.jp/outline.html"
  [2]=>
  string(32) "http://www.hirakata-p.jp/outline"
  [3]=>
  string(31) "http://www.honki-pj.com/outline"
  [4]=>
  string(57) "http://nishitetsu-sumai.com/centermarkstower/outline.html"
  [5]=>
  string(31) "http://senri100.jp/outline"
}

我添加了“/outline”,并更改了索引 -> 大纲。但是我还需要在此链接http://senri100.jp/index.html“.HTML”部分中删除一件事。

这是我使用的功能。

 function add($links){
        if (strpos($links, "https://www.finecity138.jp") === 0){
            return $links."outline.html";
        } else if (strpos($links, "outline") === false){
            return $links."outline";
        }

        return $links;
    }

    foreach ($links as $check){
        $replace[] = add($check);
    }

【问题讨论】:

  • 我已经不接受了。

标签: php url conditional


【解决方案1】:

您在第一个 if 声明之后返回

只需重新排序您的子句。

function add($links){
    if (strpos($links, "https://www.finecity138.jp") === 0){
      return $links."outline.html";
    }
    if (strpos($links, "outline") === false){
      return $links."outline";
    }

    return $links;
}

【讨论】:

    【解决方案2】:

    您的问题扩展可能有点过于宽泛,但我将仅考虑提供的示例数据来回答。看看http://php.net/manual/en/function.parse-url.php 似乎很有优势

    代码:(Demo)

    $array = [
        "http://sumiyoshi22.jp/",
        "https://www.finecity138.jp/",
        "http://www.hirakata-p.jp/",
        "http://www.honki-pj.com/",
        "http://nishitetsu-sumai.com/centermarkstower/index.html",
        "http://senri100.jp/index.html"
    ];
    
    foreach ($array as $url) {
        $parts = parse_url($url);
        $scheme = $parts["scheme"];
        $host = $parts["host"];
        $path = dirname($parts["path"]) ?? '';
        if (in_array($host, ["www.finecity138.jp", "nishitetsu-sumai.com"])) {
            $path .= ($path == "/" ? "" : "/") . "outline.html";
        } else {
            $path .= "outline";
        }
        $output[] = "{$scheme}://{$host}{$path}";
    }
    var_export($output);
    

    【讨论】:

    • 谢谢您的回答。如果你有时间,我可以再问你一件事吗?如何删除这个 HTML 单词中的“senri100.jp/outline.html”。
    • 哦,对不起。在数组中,第五项是“.html”,我正在尝试删除它。 “senri100.jp/outline.html”在同一个函数中。有可能吗?
    • 从头开始。你的输入数组看起来像这样吗? 3v4l.org/SCMZl 完成后你希望它是什么样子?你想删除元素,还是只删除字符串的结尾?
    • 我解释并给出了问题中数组的开头。希望你能理解。
    • @芭比已更新。老实说,有很多方法可以实现和修改。只有知道了每一个可能的值,我才能自信地写出一个精致的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-08
    • 1970-01-01
    • 1970-01-01
    • 2020-04-13
    • 2021-06-24
    • 1970-01-01
    相关资源
    最近更新 更多