【问题标题】:How to build this php array?如何构建这个 php 数组?
【发布时间】:2009-07-30 21:29:42
【问题描述】:
$items  = "word1 word2 word3 word4";
$items = explode(" ", $items);

$items 是我的数组,我怎样才能让它变成这个

比如我怎样才能让 word1 成为键和值?

"word1" => "word1"

【问题讨论】:

    标签: php arrays


    【解决方案1】:

    $newArray =array_combine($items, $items);

    【讨论】:

    • 这似乎是最好的方法,但它并没有像我希望的那样工作,我之前在上面发布的代码,“word1”实际上是加拿大领土,其中一些有空格,英国Columbia Manitoba New Brunswick,即 3 个位置,但我的函数将其变为数组中的 5 个值,我该如何解决这个问题?
    • 我认为您将很难将该字符串解析为数组,因为它需要了解位置。你能用不同的分隔符获取源字符串吗?
    • 你真的需要一个更好的分隔符,它永远不会在你想要检索的值中使用。也许是分号?
    【解决方案2】:
    $items  = "word1 word2 word3 word4";
    $temp = explode(" ", $items);
    $result = array();
    foreach ($temp as $value) {
      $result[$value] = $value; 
    }
    

    【讨论】:

      【解决方案3】:
      foreach($items as $item) {
      $newArr[$item] = $item;
      }
      

      【讨论】:

        猜你喜欢
        • 2017-02-03
        • 1970-01-01
        • 2017-04-25
        • 2014-03-23
        • 2016-02-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多