Creating mulitdimensional array from csv list - php

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;

Related

how do i get data from csv and put in variable and get only the value that i want

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);

Grouping in PHP using a character

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!

Converting CSV rows string into array

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);

How do I loop through this hidden field format [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
How do i Loop through the hidden field items and put in Session using PHP
I have a hidden Field which contains this format which contains the Set of rows separated by ';'(semicolon)
and each row contains some columns name separated by ':' (colon) and each column value separated by ',' (comma)
so my format would be ENO:123,ENAME:XYZ,SAL:1200; ENO:598,ENAME:AIR,SAL:1300; which is what stored in hidden field
So How do i grab each column such as ENO ,ENAME and SAL their values for any number of rows written to hidden field
so i have my own custom session function where i can set the key and value .So on looping the values
I should be able to put MyCustomSessionFunction('ENAME',??????).How do i fill this .
I did not get Proper Replies Earlier .can anyone please help me
$hiddenformat = $_POST['hiddenfield'];
string(80) "ENO:1000,ENAME:B,SAL:10;ENO:1000,ENAME:S,SAL:100;"
when i vardump($hiddenformat) I am getting the above format .How do i explode and loop and assign each value to my
custom session function
foreach( $outer_array as $outer_key => $inner_array )
{
foreach( $inner_array as $key => $value )
{
}
}
$hiddenformat = $_POST['hiddenfield'];
$parts = explode(',', $hiddenformat);
foreach($parts as $part) {
$bits = explode(':', $part);
...
}
Given a $hiddenformat of ENO:1000,ENAME:B,SAL:..., the first explode will split the line at every comma, giving you a $parts array that looks like:
$parts = array(
0 => 'ENO:1000',
1 => 'ENAME:B',
2 => 'SAL:.....
);
Yuu use foreach to loop over this $parts array, and split the $part at every colon (:). So at each stage, $bits will look like:
$bits = array(
0 => 'ENO',
1 => '1000'
)
and then on the next iteration will
$bits = array(
0 => 'ENAME',
1 => 'B'
)
and so on. What you do with those individual chunks is up to you.
And yes, this was all present in the answers of the other questions. You just had to do a bit of work to put it all together.
Yeah, it was.
It's just to say that around that, you have to explode() by ";" and in the loop use Marc's code, since there are multiple Sets of data in the string

In PHP, how do I find the value associated with a specific key

I have two arrays. One contains id=>count and the other contains id=>name. I'm trying to produce a single array that is name=>count. Any suggestions on a straightforward way to do this?
I have looked at the Array Functions in the PHP Manual and didn't see anything that stood out as doing what I want, so I'm guessing I'll need a combination of functions, but I'm having trouble coming up with something that's not convoluted.
Something like:
foreach($countA as $id => $count)
{
$newArray[$nameA[$id]] = $count;
}
This does assume that the keys are in correspondence between the two arrays, since your requirements are ambiguous otherwise.
Use array_combine...
$countArray = array(0 => 1, 1 => 5);
$namesArray = array(0 => "Bob", 1 => "Alice");
$assocArray = array_combine($namesArray, $countArray);
Edit: Here is a revised solution for the new requirements expressed in comment #2
$assocArray = array();
foreach($namesArray as $id => $name) {
$assocArray[$name] = (array_key_exists($id, $countArray)) ? $countArray[$id] : 0;
}

Categories