I am using an API that returns a CSV string as the following:
Date,Open,High,Low,Close,Volume,Adj Close 2014-06-13,3.10,3.30,3.10,3.30,6638300,3.30
I was wondering if there is an easy way to convert this CSV string to an associative array? I am familiar with working with a CSV file, but not sure what to do with a CSV file string response. I am trying to avoid writing the response to a file, just so I can read it back.
Note, writing this response to a CSV file would result in two rows and seven columns.
If the line terminator is \r\n, then first you need to explode them thru that. Then you can proces from there. Consider this example:
$data = explode("\r\n", $csv_string);
// get the headers first
$headers = array_map('trim', explode(',', array_shift($data)));
$new_data = array();
// get the values and use array combine to use the headers as keys for associative array
foreach($data as $values) {
$pieces = explode(',', $values);
// i just assigned it in an array, since we dont know how many lines of data you will receive
$new_data[] = array_combine($headers, $pieces);
}
$new_data should yield something like this:
Array
(
[0] => Array
(
[Date] => 2014-06-13
[Open] => 3.10
[High] => 3.30
[Low] => 3.10
[Close] => 3.30
[Volume] => 6638300
[Adj Close] => 3.30
)
)
Or just the usual way of handling csv strings. Use str_getcsv().
$data = str_getcsv($csv_string, "\r\n");
$headers = explode(',', array_shift($data));
$data = array_combine($headers, explode(',',reset($data)));
As others have mentioned, str_getcsv() is your friend and is an easy method to convert a CSV string into an array. This function will return an array of results. If you'd like to make it an associative array, use array_combine().
Honestly, though -- str_getcsv() may be overkill. Consider this method using explode():
// so given this string returned by the API
$api_s = "Date,Open,High,Low,Close,Volume,Adj Close\r\n2014-06-13,3.10,3.30,3.10,3.30,6638300,3.30";
// split on carriage return & line feed into two strings
$api_r = explode("\r\n", $api_s);
// split keys and values by comma
$keys = explode(',', $api_r[0]);
$vals = explode(',', $api_r[1]);
// construct associative array
$my_assoc_r = array_combine($keys, $vals);
Related
This question already has answers here:
How can I explode a string by more than one space, but not by exactly one space in php
(2 answers)
Closed 8 months ago.
I am reading from files and each line has multiple spaces. Example:
$line = 'Testing Area 1 10x10';
I need to convert it into array with 3 elements only so I can save it to a table. Final output should be like this:
$final_array = array('Testing Area', '1', '10x10');
This is how I'm doing it so far:
// read by line
foreach(explode(PHP_EOL, $contents) as $line) {
// split line by 2 spaces coz distance between `1` and `10x10` is atleast 2 spaces
$arr = explode(' ', $line);
// But because `Testing Area` and `1` has so many spaces between them,
// exploding the $line results to empty elements.
// So I need to create another array for the final output.
$final_array = array();
// loop through $arr to check if value is empty
// if not empty, push to $final array
foreach ($arr as $value) {
if (!empty($value)) {
array_push($final_array, $value);
}
}
// insert into table the elements of $final_array according to its column
}
Is there a better way to do this instead of looping through the array and checking each element if it's empty?
Take note that I have multiple files to read, each containing atleast 200 lines like that.
Use preg_split(), with 2 or more spaces as the delimiter.
$array = preg_split('/\s{2,}/', $line);
Assuming the criteria for splitting be two or more spaces, we can try using preg_split here:
$line = 'Testing Area 1 10x10';
$final_array = preg_split("/\s{2,}/", $line);
print_r($final_array);
This prints:
Array
(
[0] => Testing Area
[1] => 1
[2] => 10x10
)
I think this is a beginner's question..
I cannot find an example of this, although that may reflect that I am too naive to know what to search for..
If I have a string (the comma could be any other character):
58732,hc_p0d
58737,hc_p4
58742,hc_p4a
(new lines use "\r\n")
How can I split this into a multidimensional array (2X3 in this case, but the number of rows can vary.)
I think is the form I would want (But please suggest better ways if this is not appropriate!):
array(
array(58732,hc_p0d),
array(58737,hc_p4),
array(58742,hc_p4a),
)
The nearest I have got is using $vars = explode("\r\n",$input);
With vars looking like this (in cakephp):
(int) 0 => '58732,hc_p0d',
(int) 1 => '58737,hc_p4',
(int) 2 => '58742,hc_p4a',
(int) 3 => '58747,hc_p4b',
Thanks
If you want to convert CSV data to array format you can do it in this way
$csv = array_map('str_getcsv', file('data.csv'));
Check this reference for further explanation
http://php.net/manual/en/function.str-getcsv.php
And if it is not from file but a string containing CSV data you can do it like
$data = $csv_data;
$csv_data_rows = explode('\r\n',$data);
$final_array = array();
foreach($csv_data_rows as $key => $value){
$final_array[$key] = explode(',',$value);
}
return $final_array;
Example
I have CSV file that contains data of random number example data in CSV :
639123456789,73999999999,739222222222,839444444444,8639555555555....more
So, if I upload it, I want it to explode in a variable or in an array as long as I get the specific data. example of data I want to get is all 2 first line starting at 73 be extract so meaning all numbers that start with 73 only.
Example: 73999999999,739222222222
I have tried it by using only 1 number using split,substr and explode function but my problem is if the user input a CSV bulk data with no limit.
You can use substr() and loop through your array deleting the elements that do not match.
$str = '639123456789,73999999999,739222222222,839444444444,8639555555555';
$array = explode(',', $str); //Convert your string to an array.
$searchString = '73'; //Set the value your looking for.
foreach($array as $key=>$value){
if(substr($value, 0, 2) != $searchString){ //This will test first two characters.
unset($array[$key]);
}
}
$array = array_values($array);
print_r($array);
This will output:
Array
(
[0] => 73999999999
[1] => 739222222222
)
Updated
This will make a new array with only the numbers you want in it, leaving the original array untouched.
$str = '639123456789,73999999999,739222222222,839444444444,739222222222,839444444444,839444444444,73999999999';
$array = explode(',', $str);
$searchString = '73';
foreach($array as $key=>$value){
if(substr($value, 0, 2) == $searchString){
$results[] = $value;
}
}
print_r($results);
I have an array like:
array{
0 => string 'B.E - ECE',
1 => string 'B.E - EEE',
2 => string 'Msc - Maths',
3 => string 'Msc - Social',
}
So how can I make the array into groups like:
B.E. => ECE, EEE
Msc => Maths,Social
?
I want to do it in PHP. Can anybody help me how to achieve it ?
So is your array split by the "-" character?
so it's Key - Value pairs split by commas?
Ok -
(edit: section removed to clarify answer)
Following conversation and some rearrangement of the question, a second try at a solution, with the above assumptions, try this:
$array = array {
0 => string 'B.E - ECE' (length=9)
1 => string 'B.E - EEE' (length=9)
2 => string 'Msc - Maths' (length=11)
3 => string 'Msc - Social' (length=12)
}
foreach ($array as $row){
$piece = explode("-",$row);
$key = $piece[0];
$newArray[$key][] = $piece[1];
unset($piece);
}
unset($row) ///tidy up
This will output two arrays each of two arrays:
$newArray[Msc] = array("Maths","Social");
$newArray[B.E] = array("ECE","EEE");
What I did was cause the Foreach loop to automatically add onto the array if the key exists with $newArray[$key][] so that the values are automatically collected by key, and the key is defined as the first half of the original array values.
Printing:
To print the result:
foreach($newArray as $key=>$newRow){
/// there are two rows in this case, [B.E] and [MSc]
print $key.":<br>";
print "<pre>";
///<pre> HTML tag makes output use linebreaks and spaces. neater.
print_r($newRow);
///alternatively use var_dump($newRow);
print "</pre>";
}
Alternatively if you wish to print a known named variable you can write:
print_r($newArray['B.E']);
Which will print all the data in that array. print_r is very useful.
what you want is php's explode. Not sure if this will give you the perfect answer but should give you an idea of what to do next.
$groupedArray = array();
foreach($array as $row){
$split = explode(" - ",$row);
$groupedArray[] = $split[0];
}
array_unique($groupedArray); //This will give you the two groupings
foreach($array as $row){
$split = explode(" - ",$row);
$pos = array_search($split[0],$groupedArray);
if($pos !== FALSE){
$groupedArray[$pos][] = $split[1];
}
}
This should give you a full formatted array called $groupedArray where $array is the array you already have.
Hope this helps!
I am new PHP question and I am trying to create an array from the following string of data I have. I haven't been able to get anything to work yet. Does anyone have any suggestions?
my string:
Acct_Status=active,signup_date=2010-12-27,acct_type=GOLD,profile_range=31-35
I want to dynamically create an array called "My_Data" and have id display something like my following, keeping in mind that my array could return more or less data at different times.
My_Data
(
[Acct_Status] => active
[signup_date] => 2010-12-27
[acct_type] => GOLD
[profile_range] => 31-35
)
First time working with PHP, would anyone have any suggestions on what I need to do or have a simple solution? I have tried using an explode, doing a for each loop, but either I am way off on the way that I need to do it or I am missing something. I am getting something more along the lines of the below result.
Array ( [0] => Acct_Status=active [1] => signup_date=2010-12-27 [2] => acct_type=GOLD [3] => profile_range=31-35} )
You would need to explode() the string on , and then in a foreach loop, explode() again on the = and assign each to the output array.
$string = "Acct_Status=active,signup_date=2010-12-27,acct_type=GOLD,profile_range=31-35";
// Array to hold the final product
$output = array();
// Split the key/value pairs on the commas
$outer = explode(",", $string);
// Loop over them
foreach ($outer as $inner) {
// And split each of the key/value on the =
// I'm partial to doing multi-assignment with list() in situations like this
// but you could also assign this to an array and access as $arr[0], $arr[1]
// for the key/value respectively.
list($key, $value) = explode("=", $inner);
// Then assign it to the $output by $key
$output[$key] = $value;
}
var_dump($output);
array(4) {
["Acct_Status"]=>
string(6) "active"
["signup_date"]=>
string(10) "2010-12-27"
["acct_type"]=>
string(4) "GOLD"
["profile_range"]=>
string(5) "31-35"
}
The lazy option would be using parse_str after converting , into & using strtr:
$str = strtr($str, ",", "&");
parse_str($str, $array);
I would totally use a regex here however, to assert the structure a bit more:
preg_match_all("/(\w+)=([\w-]+)/", $str, $matches);
$array = array_combine($matches[1], $matches[2]);
Which would skip any attributes that aren't made up of letters, numbers or hypens. (The question being if that's a viable constraint for your input of course.)
$myString = 'Acct_Status=active,signup_date=2010-12-27,acct_type=GOLD,profile_range=31-35';
parse_str(str_replace(',', '&', $myString), $myArray);
var_dump($myArray);