Turning String Into Array [duplicate] - php

This question already has answers here:
Convert backslash-delimited string into an associative array
(4 answers)
Closed 6 years ago.
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.

$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];
}

$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 !!!

Related

Create groups of values from array values [duplicate]

This question already has answers here:
Finding the subsets of an array in PHP
(5 answers)
Closed 7 years ago.
I will do my best to explain this idea to you. I have an array of values, i would like to know if there is a way to create another array of combined values. So, for example:
If i have this code:
array('ec','mp','ba');
I would like to be able to output something like this:
'ec,mp', 'ec,ba', 'mp,ba', 'ec,mp,ba'
Is this possible? Ideally i don't want to have duplicate entries like 'ec,mp' and 'mp,ec' though, as they would be the same thing
You can take an arbitrary decision to always put the "lower" string first. Once you made this decision, it's just a straight-up nested loop:
$arr = array('ec','mp','ba');
$result = array();
foreach ($arr as $s1) {
foreach ($arr as $s2) {
if ($s1 < $s2) {
$result[] = array($s1, $s2);
}
}
}
You can do it as follows:
$arr = array('ec','mp','ba', 'ds', 'sd', 'ad');
$newArr = array();
foreach($arr as $key=>$val) {
if($key % 2 == 0) {
$newArr[] = $val;
} else {
$newArr[floor($key/2)] = $newArr[floor($key/2)] . ',' . $val;
}
}
print_r($newArr);
And the result is:
Array
(
[0] => ec,mp
[1] => ba,ds
[2] => sd,ad
)
Have you looked at the function implode
<?php
$array = array('ec','mp','ba');
$comma_separated = implode(",", $array);
echo $comma_separated; // ec,mp,ba
?>
You could use this as a base for your program and what you are trying to achieve.

How to join into a comma-separated string from array of arrays (multidimensional-array)? [duplicate]

This question already has answers here:
Implode a column of values from a two dimensional array [duplicate]
(3 answers)
Closed 7 months ago.
Ok, I know that to get a comma-seperated string from a string array in PHP you could do
$stringA = array("cat","dog","mouse");
$commaSeperatedS = join(',', $stringA);
But what if I have an array of arrays(not a simple string array)?
$myAssociativeA =
array(
[0] => array("type"=>"cat", "sex"=>"male")
, [1] => array("type"=>"dog", "sex"=>"male")
);
and my goal is to get a comma-seperated string from a specific property in each array, such as "type"? Ive tried
$myGoal = join(',', $myAssociativeA{'type'});
My target value for $myGoal in this case would be "cat,dog".
Is there a simple way without having to manually loop through each array, extract the property, then do a join at the end?
This should work for you:
(Here I just get the column which you want with array_column() and simply implode it with implode())
echo implode(",", array_column($myAssociativeA, "type"));
Another option is to use array_walk() to return the key you want:
array_walk($myAssociativeA, function(&$value, $key, $return) {
$value = $value[$return];
}, 'type');
echo implode(', ', $myAssociativeA); // cat, dog
Useful for older PHP versions - #Rizier123's answer using array_column() is great for PHP 5.5.0+
You can use this if you have PHP < 5.5.0 and >= 5.3.0 (thanks to #Rizier123) and you can't use array_column()
<?php
$myAssociativeA = array(array("type"=>"cat", "sex"=>"male"), array("type"=>"dog", "sex"=>"male"));
$myGoal = implode(',', array_map(function($n) {return $n['type'];}, $myAssociativeA));
echo $myGoal;
?>
EDIT: with the recommendation in the comment of #scrowler the code now is:
<?php
$myAssociativeA = array(array("type"=>"cat", "sex"=>"male"), array("type"=>"dog", "sex"=>"male"));
$column = 'type';
$myGoal = implode(',', array_map(function($n) use ($column) {return $n[$column];}, $myAssociativeA));
echo $myGoal;
?>
Output:
cat,dog
Read more about array_map in:
http://php.net/manual/en/function.array-map.php
You just have to loop over the array and generate the string yourself.
<?php
$prepend = '';
$out = '';
$myAssociativeA = array(
array('type' => 'cat'),
array('type' => 'dog')
);
foreach($myAssociativeA as $item) {
$out .= $prepend.$item['type'];
$prepend = ', ';
}
echo $out;
?>
You could easily turn this into a function.
<?php
function implode_child($array,$key) {
$prepend = '';
$out = '';
foreach($array as $item) {
$out .= $prepend.$item[$key];
$prepend = ', ';
}
return $out;
}
?>
Ok, under assumption that your assoc array fields are ordered always the same way you could use snippet like this. Yet you still need to iterate over the array.
$csvString = "";
foreach ( $myAssociativeA as $row ) {
$csvRow = implode(",", $row);
$csvString .= $csvRow . PHP_EOL;
}
Now if you don't want to store whole CSV in a variable (which you should not do) take a look at http://www.w3schools.com/php/func_filesystem_fputcsv.asp and see an example how to put it directly into the file.

Cut text on pieces by 2 sentences PHP [duplicate]

This question already has answers here:
php - explode string at . but ignore decimal eg 2.9
(2 answers)
Closed 9 years ago.
I have a long string of text. I want to store it in an array by 2 sentences per element. I think it should be done by exploding the text around dot+space; however, there are elements like 'Mr.' which I don't know how to exclude from the explode function.
I also don't know how to adjust it to explode the text by 2 sentences, not by 1.
maybe something like:
$min_sentence_length = 100;
$ignore_words = array('mr.','ms.');
$text = "some texing alsie urj skdkd. and siks ekka lls. lorem ipsum some.";
$parts = explode(" ", $text);
$sentences = array();
$cur_sentence = "";
foreach($parts as $part) {
// Check sentence min length and is there period
if (strlen($cur_sentence) > $min_sentence_length &&
substr($part,-1) == "." && !in_array($part, $ignore_words)) {
$sentences[] = $cur_sentence;
$cur_sentence = "";
}
$cur_sentence .= $part . " ";
}
if (strlen($cur_sentence) > 0)
$sentences[] = $cur_sentence;
The comments on your question link to answers that use preg_split() instead of explode() to provide more accurate description of how and when to split the input. That might work for you. Another approach would be to split your input on every occurrence of ". " into a temporary array, then loop through that array, piecing it back together however you like. e.g.
$tempArray = explode('. ', $input);
$outputArray = array();
$outputElement = '';
$sentenceCount = 0;
foreach($tempArray as $part){
$outputElement .= $part . '. ';
//put other exceptions here, not just "Mr."
if ($part != 'Mr'){
$sentenceCount++;
}
if ($senteceCount == 2){
$outputArray[] = $outputElement;
$outputElement = '';
$sentenceCount = 0;
}
}

php exploded associative array problem

I have php script as below;
$ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34);
$ages2 = '"Peter"=>32, "Quagmire"=>30, "Joe"=>34';
$array = explode(",", $ages2);
echo $array["Peter"];
echo $ages["Peter"];
In this case, echo $ages["Peter"]; is working well, but echo $array["Peter"]; is not working. Can anybody solve this please..
Thanks in advance.
blasteralfred
You'll have to go in two steps :
First, explode using ', ', as a separator ; to get pieces of data such as "Peter"=>32
And, then, for each value, explode using '=>' as a separator, to split the name and the age
Removing the double-quotes arround the name, of course.
For example, you could use something like this :
$result = array();
$ages2 = '"Peter"=>32, "Quagmire"=>30, "Joe"=>34';
foreach (explode(', ', $ages2) as $couple) {
list ($name, $age) = explode('=>', $couple);
$name = trim($name, '"');
$result[$name] = $age;
}
var_dump($result);
And, dumping the array, you'd get the following output :
array
'Peter' => string '32' (length=2)
'Quagmire' => string '30' (length=2)
'Joe' => string '34' (length=2)
Which means that using this :
echo $result['Peter'];
Would get you :
32
Of course it doesn't work. explode just splits by the given delimiter but doesn't create an associative array.
Your only hope if you really have such a string is to parse it manually. Either using preg_match_all, or I suppose you could do:
$array = eval('return array('.$ages2.');');
But of course this isn't recommended since it could go wrong in many many ways.
In any case I'm pretty sure you can refactor this code or give us more context if you need more help.
You'll need to build the array yourself by extracting the name and age:
<?php
$array = array();
$ages2 = '"Peter"=>32, "Quagmire"=>30, "Joe"=>34';
foreach (explode(",", $ages2) as $element) {
$parts = explode("=>", $element);
if (count($parts) == 2) {
$name = str_replace(array('"', ' '), '', $parts[0]);
$age = (int) $parts[1];
$array[$name] = $age;
}
}
print_r($array);
$ages2 is not an array, so what you're trying here won't work directly, but you can transform a string with that structure into an array like this:
$ages2 = '"Peter"=>32, "Quagmire"=>30, "Joe"=>34';
$items = explode(",", $ages2);
foreach ($items as $item) {
list($key,$value) = explode('=>',$item);
$key = str_replace('"','',trim($key)); // Remove quotes and trim whitespace.
$array[$key] = (int)$value;
}
If you var_dump($array), you'll have:
array(3) {
["Peter"]=>
int(32)
["Quagmire"]=>
int(30)
["Joe"]=>
int(34)
}
So you can do this as expected and get 32 back out:
echo $array['Peter']

Combine Arrays and update a string with values

I have two issues I was hoping to get help on:
Combine two arrays into one string
and add some formatting
insert the new string into a
specific spot in a bigger string.
I have two arrays:
$array_1 = array("100","200","300");
$array_2 = array("abc","def","ghi");
$result = array_merge($array_1, $array_2);
foreach ($result as $val){
//NEED HELP HERE create a string that adds a "mac=" to the beginning of the current $val and adds a "/n" to the end of the current value.
}
The above should somehow create the string below:
$my_string = "mac=100/n
mac=200/n
mac=300/n
mac=abc/n
mac=def/n
mac=ghi/n";
Now for Part #2
I have a current string that was created already:
$current_String = "[MACS]/n
mac=blah1/n
mac=blah2/n
mac=blah3/n
[SERVICES]";
My last issue is to replace everything between [MACS]/n and [SERVICES] with $my_string
So I should end up with:
$updated_String = "[MACS]/n
mac=100/n
mac=200/n
mac=300/n
mac=abc/n
mac=def/n
mac=ghi/n
[SERVICES]";
Any help or insight would be greatly appreciated.
This should work:
$array_1 = array("100","200","300");
$array_2 = array("abc","def","ghi");
$result = array_merge($array_1, $array_2);
$myString = "[MACS]/n\nmac=" . implode($result, "/n\nmac=") . "/n\n[SERVICES]";
//replace in other string
$macsIndex = strrpos($currentString, "[MACS]");
$servicesIndex = strrpos($currentString, "[SERVICES]");
$currentString = substr($currentString, 0, $macsIndex) . $myString . substr($currentString, servicesIndex+10);
Outputs:
[MACS]/n
mac=100/n
mac=200/n
mac=300/n
mac=abc/n
mac=def/n
mac=ghi/n
[SERVICES]
$formatted = '';
foreach ($result as $val){
$val = sprintf("mac=%s\n", $val);
$formatted .= $val;
}

Categories