【问题标题】:Turning String Into Array [duplicate]将字符串转换为数组 [重复]
【发布时间】:2016-08-23 13:05:43
【问题描述】:

我已经设法将以下字符串整理成清晰的格式:

string(191) "twitter:3 facebookshare_count:5 like_count:0 comment_count:0 total_count:8 click_count:5 buffer:0 pinterest:0 linkedin:0 stumbleupon:0 redditscore:0 ups:8 downs:3 google:4 delicious:0 digg:0 "

我现在正在尝试使用它并创建一个数组,以便每个数字都与其平台相关联。

$shares = array(
'twitter' => 3,
'facebookshare_count' => 5,
'like_count' => 0
)

等等……

我一直在研究爆炸功能,使用空格作为分隔符,但我真的很困惑如何实现这个最终结果。

我对 PHP 比较陌生,并且很难找到用于搜索此问题的单词。我不知道“数组”或“对象”是否是正确的术语。

【问题讨论】:

    标签: php


    【解决方案1】:
    $str = 'twitter:3 facebookshare_count:5 like_count:0 comment_count:0 total_count:8 click_count:5 buffer:0 pinterest:0 linkedin:0 stumbleupon:0 redditscore:0 ups:8 downs:3 google:4 delicious:0 digg:0';
    
    $strArray = explode(' ', $str);
    $desiredArray = [];
    foreach ($strArray as $value) {
        $value = explode(":", $value);
        $desiredArray[$value[0]] = $value[1];
    }
    

    【讨论】:

      【解决方案2】:
      $myString = "twitter:3 facebookshare_count:5 like_count:0 comment_count:0 total_count:8 click_count:5 buffer:0 pinterest:0 linkedin:0 stumbleupon:0 redditscore:0 ups:8 downs:3 google:4 delicious:0 digg:0";
      
      $parseString = explode(" ", $myString);
      $newArray = [];
      
      foreach($parseString as $item) {
          $splitItem = explode(":", $item);
          $newArray[$splitItem[0]] = $splitItem[1];
      }
      
      foreach($newArray as $key=>$data) {
          echo $key . " " . $data . "<br>";
      }
      

      希望对你有帮助!!!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-12-05
        • 1970-01-01
        • 2021-08-20
        • 2012-05-18
        • 2014-07-07
        • 2017-10-09
        相关资源
        最近更新 更多