How to read a CSV string into an array [duplicate] - php

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How can I split a comma delimited string into an array in PHP?
extract tags (words) from whole string
I'm trying to read a long variable into an array.
Variable $x = "text1", "text2", "text3", etc...
$x = '"text1", "text2", "text3"';
Do I just call it into my array like:
array($x)?
This doesn't seem to work
I want the final product to be:
array("text1", "text2", "text3")
What am I doing wrong? Thanks!
EDIT:
Ok, some specifics:
I'm trying to replace the date fields in the following array with many dynamically read dates:
$myCalendar->setSpecificDate(array("2012-09-09", "2012-09-10"), 1, '');
I have the dynamically read dates in a variable $x. When I echo $x, I get something in the format "2012-09-09", "2012-09-10", "2012-09-09", "2012-09-10", "2012-09-09", "2012-09-10", etc
Thanks

If your variable is a string like:
$x = '"text1", "text2", "text3"'
You can convert it to an array with str_getcsv like the following:
$x = '"text1", "text2", "text3"';
$yourArray = str_getcsv($x);

If your input string is '"text1", "text2", "text3"'
You can use the following code to get an array with three string
print_r(
explode( ",", preg_replace('/[" ]*/', "", '"text1", "text2", "text3"'))
);
// Outputs Array ( [0] => text1 [1] => text2 [2] => text3 )
This assumes there are no spaces in your strings, you'll have to play with it if spaces are allowed

Explode it. String becomes an array based on a delimiter.
$x = "text1,text2,text3";
$new_array = explode(',', $x);
This becomes:
Array
(
[0] => text1
[1] => text2
[2] => text3
)

Related

Merge data into an array then count the array values

I need to merge data into an array, then count the array values.
$str = '"Cat","A","A","A","A"';
$abc = [
$str,
"A",
"Cat",
"Dog",
"A",
"Dog"
];
print_r(array_count_values($abc));
Result came out:
Array ( ["Cat","A","A","A","A"] => 1 [A] => 2 [Cat] => 1 [Dog] => 2 )
But I need like this way:
Array ( [A] => 6 [Cat] => 2 [Dog] => 2 )
This is because $str is a string and not an array. So this is added into the $abc array as one element.
You can convert in into an array with the explode function:
$str = '"Cat","A","A","A","A"';
$arr = explode(',', $str);
// So $arr is Array([0] => "Cat", [1] => "A", [2] => "A", [3] => "A", [4] => "A")
Then you need to remove the double quotes around each element.
I suggest to use the trim function, and the array_map, to apply it to each element:
$arr = array_map(function ($item) { return trim($item, '"'); }, $arr);
// $arr is Array([0] => Cat, [1] => A, [2] => A, [3] => A, [4] => A)
Then you can merge it with the rest of values:
$abc = array_merge($arr, array("A","Cat","Dog","A","Dog"));
print_r(array_count_values($abc));
// Should be Array ( [A] => 6 [Cat] => 2 [Dog] => 2 )
Well, then, don't put a string into an array and expect it to be treated as array values. Either modify the string to be an array, and merge the two arrays, or parse the string and add each value to the array.
For the latter approach, you can do something like:
$str = '"Cat","A","A","A","A"';
$abc = array("A","Cat","Dog","A","Dog");
$splitstr = explode(',',str_replace('"','',$str));
$finalarray = array_merge($abc,$splitstr);
print_r(array_count_values($finalarray));
Your logic is flawed, you should first create array properly
$str = '"Cat","A","A","A","A"';
$abc = array("A","Cat","Dog","A","Dog");
$splitstr = explode(',',str_replace('"','',$str));
$finalarray = array_merge($abc,$splitstr);
print_r(array_count_values($finalarray));
Now you will get the desired result.
Because your quote-wrapped, comma-delimited string closely resembles a json string, I reckon it will be most direct/performant to just wrap the whole string in square braces, then json_decode it and spread it into the array (so that elements are injected into the array one at a time).
Code: (Demo)
$str = '"Cat","A","A","A","A"';
$abc = [
...json_decode("[$str]"),
"A",
"Cat",
"Dog",
"A",
"Dog"
];
print_r(array_count_values($abc));
you put first element as string completely. make it separate
$str = '"Cat","A","A","A","A"';
$abc=array( "Cat","A","A","A","A", "A","Cat","Dog","A","Dog");
print_r(array_count_values($abc));
Or merge array
$arr1 = ["Cat","A","A","A","A"];
$abc=array_merge( $arr1,["A","Cat","Dog","A","Dog"]);
print_r(array_count_values($abc));
Demo
You are using array_count_values to count all the values of the $abc array. However, $str is a string and not an array, but an element of the $abc array.
The simplest solutions is to convert $str into an array by removing " double quotes (with str_replace method) and splitting substrings using , as a delimiter (with explode method). This can be done just by adding a single line as shown in this snippet:
$str = '"Cat","A","A","A","A"';
// Converts $str into an array of strings
$str_array = explode(',',str_replace('"','',$str));
$abc = array_merge($str_array, array("A","Cat","Dog","A","Dog"));
print_r(array_count_values($abc));
You can see the execution of this script in this link.
According to the PHP manual, you can use array_merge ( array $array1 [, array $... ] )
example:
$str = '"Cat","A","A","A","A"';
$abc=array_merge($str, array("A","Cat","Dog","A","Dog"));
print_r(array_count_values($abc));

PHP from string to multiple arrays at the hand of placeholders

Good day,
I have an I think rather odd question and I also do not really know how to ask this question.
I want to create a string variable that looks like this:
[car]Ford[/car]
[car]Dodge[/car]
[car]Chevrolet[/car]
[car]Corvette[/car]
[motorcycle]Yamaha[/motorcycle]
[motorcycle]Ducati[/motorcycle]
[motorcycle]Gilera[/motorcycle]
[motorcycle]Kawasaki[/motorcycle]
This should be processed and look like:
$variable = array(
'car' => array(
'Ford',
'Dodge',
'Chevrolet',
'Corvette'
),
'motorcycle' => array(
'Yamaha',
'Ducati',
'Gilera',
'Kawasaki'
)
);
Does anyone know how to do this?
And what is it called what I am trying to do?
I want to explode the string into the two arrays. If it is a sub array
or two individual arrays. I do not care. I can always combine the
latter if I wish so.
But from the above mentioned string to two arrays. That is what I
want.
Solution by Dlporter98
<?php
///######## GET THE STRING FILE OR DIRECT INPUT
// $str = file_get_contents('file.txt');
$str = '[car]Ford[/car]
[car]Dodge[/car]
[car]Chevrolet[/car]
[car]Corvette[/car]
[motorcycle]Yamaha[/motorcycle]
[motorcycle]Ducati[/motorcycle]
[motorcycle]Gilera[/motorcycle]
[motorcycle]Kawasaki[/motorcycle]';
$str = explode(PHP_EOL, $str);
$finalArray = [];
foreach($str as $item){
//Use preg_match to capture the pieces of the string we want using a regular expression.
//The first capture will grab the text of the tag itself.
//The second capture will grab the text between the opening and closing tag.
//The resulting captures are placed into the matches array.
preg_match("/\[(.*?)\](.*?)\[/", $item, $matches);
//Build the final array structure.
$finalArray[$matches[1]][] = $matches[2];
}
print_r($finalArray);
?>
This gives me the following array:
Array
(
[car] => Array
(
[0] => Ford
[1] => Dodge
[2] => Chevrolet
[3] => Corvette
)
[motorcycle] => Array
(
[0] => Yamaha
[1] => Ducati
[2] => Gilera
[3] => Kawasaki
)
)
The small change I had to make was:
Change
$finalArray[$matches[1]] = $matches[2]
To:
$finalArray[$matches[1]][] = $matches[2];
Thanks a million!!
There are many ways to convert the information in this string to an associative array.
split the string on the new line into an array using the explode function:
$str = "[car]Ford[/car]
[car]Dodge[/car]
[car]Chevrolet[/car]
[car]Corvette[/car]
[motorcycle]Yamaha[/motorcycle]
[motorcycle]Ducati[/motorcycle]
[motorcycle]Gilera[/motorcycle]
[motorcycle]Kawasaki[/motorcycle]";
$items = explode(PHP_EOL, $str);
At this point each delimited item is now an array entry.
Array
(
[0] => [car]Ford[/car]
[1] => [car]Dodge[/car]
[2] => [car]Chevrolet[/car]
[3] => [car]Corvette[/car]
[4] => [motorcycle]Yamaha[/motorcycle]
[5] => [motorcycle]Ducati[/motorcycle]
[6] => [motorcycle]Gilera[/motorcycle]
[7] => [motorcycle]Kawasaki[/motorcycle]
)
Next, loop over the array and pull out the appropriate pieces needed to build the final associative array using the preg_match function with a regular expression:
$finalArray = [];
foreach($items as $item)
{
//Use preg_match to capture the pieces of the string we want using a regular expression.
//The first capture will grab the text of the tag itself.
//The second capture will grab the text between the opening and closing tag.
//The resulting captures are placed into the matches array.
preg_match("/\[(.*?)\](.*?)\[/", $item, $matches);
//Build the final array structure.
$finalArray[$matches[1]] = $matches[2]
}
The following is an example of what will be found in the matches array for a given iteration of the foreach loop.
Array
(
[0] => [motorcycle]Gilera[
[1] => motorcycle
[2] => Gilera
)
Please note that I use the PHP_EOL constant to explode the initial string. This may not work if the string was pulled from a different operating system than the one you are running this code on. You may need to replace this with the actual end of line characters that is being used by the string.
Why don't you create two separate arrays?
$cars = array("Ford", "Dodge", "Chevrolet", "Corvette");
$motorcycle = array("Yamaha", "Ducati", "Gilera", "Kawasaki");
You could also use an Associative array to do this.
$variable = array("Ford"=>"car", "Yamaha"=>"motorbike");

Convert array to comma separated values

I'm using PHP.
I have the following array:
Array
(
[home] => 9
[pets] => 8
[dogs] => 7
[shampoo] => 7
[cover] => 6
)
I want to create a comma separated list which is:
home,pets,dogs,shampoo,cover
Here's what I'm trying but giving me blank string ($words is the array):
$myWords = implode(',',$words[0]);
Do I need to loop instead?
You're close. You just need the keys from that array. array_keys() will do that for you:
$myWords = implode(',',array_keys($words));
$string = implode(',', array_keys($words));
$words[0] does not exist in your array, because all of your keys are strings.

PHP preg_split delimiter pattern, split at character chain [duplicate]

This question already has answers here:
Explode string by one or more spaces or tabs
(8 answers)
Closed 7 months ago.
With the following string:
$str = '["one","two"],a,["three","four"],a,,a,["five","six"]';
preg_split( delimiter pattern, $str );
How would I have to set up the delimiter pattern to obtain this result:
$arr[0] = '["one","two"]';
$arr[1] = '["three","four"]';
$arr[2] = '["five","six"]';
In other words, is there a way to split at the pattern ',a,' AND ',a,,a,' BUT check for ',a,,a,' first because ',a,' is a sub string of ',a,,a,'?
Thanks in advance!
If it can only be ,a, and ,a,,a,, then this should be enough:
preg_split("/(,a,)+/", $str);
It looks like what you're actually trying to do is separate out the square bracketed parts. You could do that like so:
$arr = preg_split("/(?<=\])[^[]*(?=\[)/",$str);
Take a look at this code:
$result = array();
preg_match_all("/(\[[^\]]*\])/", '["one","two"],a,["three","four"],a,,a,["five","six"]', $result);
echo '<pre>' . print_r($result, true);
It will return:
Array
(
[0] => Array
(
[0] => ["one","two"]
[1] => ["three","four"]
[2] => ["five","six"]
)
[1] => Array
(
[0] => ["one","two"]
[1] => ["three","four"]
[2] => ["five","six"]
)
)

trying to filter string with <br> tags using explode, does not work

I get a string that looks like this
<br>
ACCEPT:YES
<br>
SMMD:tv240245ce
<br>
is contained in a variable $_session['result']
I am trying to parse through this string and get the following either in an array or as separate variables
ACCEPT:YES
tv240245ce
I first tried
to explode the string using as the delimiter, and that did not work
then I already tried
$yes = explode(":", strip_tags($_SESSION['result']));
echo print_r($yes);
which gives me an array like so
Array ( [0] => ACCEPT [1] => YESSEED [2] => tv240245ce ) 1
which gives me one of my answers.
Please what would be a great way of trying to achieve what I am trying to achieve?
is there a way to get rid of the first and last?
then use the remaining one as a delimiter to explode the string ?
or what's the best way to go about this ?
This will do it:
$data=preg_split('/\s?<br>\s?/', str_replace('SMMD:','',$data), NULL, PREG_SPLIT_NO_EMPTY);
See example here:
CodePad
You can also skip caring about the spurious <br> and treat the whole string as key:value format with a simple regex like:
preg_match_all('/^(\w+):(.*)/', $text, $result, PREG_SET_ORDER);
This requires that you really have line breaks in it though. Gives you a $result list which is easy to convert into an associative array afterwards:
[0] => Array
(
[0] => ACCEPT:YES
[1] => ACCEPT
[2] => YES
)
[1] => Array
(
[0] => SMMD:tv240245ce
[1] => SMMD
[2] => tv240245ce
)
First, do a str_replace to remove all instances of "SMMD:". Then, Explode on "< b r >\n". Sorry for weird spaced, it was encoding the line break.
Include the new line character and you should get the array you want:
$mystr = str_replace( 'SMMD:', '', $mystr );
$res_array = explode( "<br>\n", $mystr );

Categories