-2

I have the following string which I've managed to get cleaned up into a clear format:

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 "

I am now trying to take this and create an array so each digit is associated with its platform.

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

and so on...

I've been looking at the explode function, using spaces as the delimiter, but I'm really stuck on how to achieve this end result.

I am relatively new to PHP, and struggling to find the words to use to search for this problem. I don't know if 'array' or 'object' is even the right terminology here.

Amarendra Kumar
  • 858
  • 9
  • 16
Nick
  • 876
  • 1
  • 14
  • 35

2 Answers2

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];
}
Gareth Parker
  • 5,012
  • 2
  • 18
  • 42
0
$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>";
}

Hope it helps !!!

Osama Yawar
  • 361
  • 2
  • 6
  • 19