I have a csv file which has a word for each row like this
word1
word2
word3
And have the following code to read the data:
$arr = array();
$fh = fopen('path/to/file', 'r');
while (($rows = fgetcsv($fh)) !== false) {
print_r($rows);
if (!in_array($rows[0], $arr))
$arr[] = "'".trim($rows[0])."'";
}
fclose($fh);
print_r($arr);
The problem is im getting empty strings/null for $rows[0] and im quite sure the data is there.
Array ( [0] => )
Array ( [0] => )
Array ( [0] => )
Array ( [0] => '' [1] => '' [2] => '' [3] => '' )
Any help would be greatly appreciated.
You're trying to read the words into an array? Replace all that with just:
$arr = file('/path/to/file');
print_r($arr);
Cannot reproduce. I'm assuming there is something wrong with your file format. Most likely there is an empty line on top (which I'm not quite sure, but might fail the !== false test).
Better try:
$arr = array_map("str_getcsv", file("words.csv"));
print_r($arr);
And if you need to re-add the quotes, do a separate loop.
The file reading part has already been answered, but about your loop to add the quotes, you could use array_walk():
function add_quotes(&$item)
{
$item = "'" . $item . "'";
}
array_walk($arr, "add_quotes");
Related
Thank you for the response. I will give it a try and update my question, I have my own code but it is a bit messy to show all. My problem is that I do not get the indexes right.
I use:
$products = array();
$lines = file('data_stock.csv', FILE_IGNORE_NEW_LINES);
foreach ($lines as $key => $value)
{
$products[$key] = str_getcsv($value);
}
And I manage to read the data, but this will give me an error:
if ((int)$products[$_sku] > 0 && isset($products[$_sku])) {
Error: Notice: Undefined index: test-product-1 in....
The 'test-product-1' is from the sku column in the csv file
Output from
echo '<pre>';
print_r($products);
echo '</pre>';
gives:
Array
(
[0] => Array
(
[0] => sku
[1] => qty
)
[1] => Array
(
[0] => test-product-1
[1] => 3
)
[2] => Array
(
[0] => test-product-2
[1] => 6
)
[3] => Array
(
[0] => test-product-3
[1] => 30
)
)
I am trying to use a csv file to be imported into the array to replace
$products = [
'test-product-1' => 3,
'test-product-2' => 6,
'test-product-3' => 30
];
But I can not produce the same array when I import from the CSV file, which will cause problems. Examples for CSV to array: http://php.net/manual/en/function.str-getcsv.php
CSV file:
sku,qty
test-product-1,3
test-product-2,6
test-product-3,30
Next step is to extend the script to handle prices. I need to be able to pick up these variables from the CSV file too. And use them inside the for loop.
sku,qty,price,special_price
test-product-1,3,100,50
test-product-2,6,99,
test-product-3,30,500,300
I think the problem is that when you store the row, your storing it indexed by the row number ($key will be the line number in the file). Instead I think you want to index it by the first column of the CSV file. So extract the data first (using str_getcsv() as you do already) and index by the first column ([0])...
$products = array();
$lines = file('data_stock.csv', FILE_IGNORE_NEW_LINES);
foreach ($lines as $value)
{
$data = str_getcsv($value);
$products[$data[0]] = $data;
}
If you want to add the first row as a header and use it to key the data...
$products = array();
$lines = file('data_stock.csv', FILE_IGNORE_NEW_LINES);
$headers = str_getcsv(array_shift($lines));
$products = array();
foreach ( $lines as $value ) {
$data = str_getcsv($value);
$products[$data[0]] = array_combine($headers, $data);
}
The removes the first row of the array using array_shift() and then uses this row in the array_combine() as the keys for each row. With your test data, you would get something like...
Array
(
[test-product-1] => Array
(
[sku] => test-product-1
[qty] => 3
[price] => 100
[special_price] => 50
)
I used following code in my project and its working fine for me.
I used csv_reader PHP library for it.
You have to put this library in your library folder and import it into file where you want to read your csv.
include_once('../csv_reader.php');
$read = new CSV_Reader;
$read->strFilePath = "file_name_with_path";
$read->strOutPutMode = 0; // 1 will show as HTML 0 will return an array
$read->setDefaultConfiguration();
$read->readTheCsv();
$dataArr = array();
$dataArr = $read->arrOutPut;
In $dataArr, i will get the result,
I have a .csv file with list of bank numbers and bank names like this
10000000;BBk Berlin
10010010;Postbank Berlin
10010111;SEB Berlin
10010424;Aareal Bank
.......
and when I use fgetscv() like this:
$filename = bank.csv;
if (file_exists($filename) && $file = fopen($filename, "r")) {
while( !feof($file) ) {
print_r(fgetcsv($file));
}
}
This will get me an array with single key like this
Array
(
[0] => 10000000;BBk Berlin
)
Array
(
[0] => 10010010;Postbank Berlin
)
Array
(
[0] => 10010111;SEB Berlin
)
Array
(
[0] => 10010424;Aareal Bank
)
And what i want is this:
Array
(
[0] => 10000000 [1] => BBk Berlin
)
So that the bank name is a separate key in array. How can i achieve this? Maybe fgetcsv() is not the right function for me?
The third parameter of fgetcsv is the delimiter, so you must set it accordingly
fgetcsv($file, 0, ';')
Your problem is, that fgetcsv uses , comma as delimiter by default. You need to change it to ; semicolon. Then you won't need to explode anymore :)
function process_csv($file) {
$file = fopen($file, "r");
$data = array();
while (!feof($file)) {
$data[] = fgetcsv($file,null,';');
}
fclose($file);
return $data;
}
Example :
Array
(
[0] => "example.fr", "2013-08-24", "test"
[1] => "toto.com, "2014-10-01", "test2"
)
How can I do to split this array every comma ? I would like to get every word in quotes into a variable like this :
$var1= "example.fr";
$var2= "2013-08-24";
$var3 = "test";
....
EDIT: The structure of the array is GOOD ! Every element is enclosed in quotes in ONLY one array ! Like CSV file
Don't reinvent a CSV parser, use the existing functionality.
From PHP 5.3+:
$parsed = array_map('str_getcsv', $array);
http://php.net/str_getcsv
Before 5.3:
$fh = fopen('php://temp', 'r+');
$parsed = array();
foreach ($array as $row) {
ftruncate($fh, 0);
fwrite($fh, $row);
rewind($fh);
$parsed[] = fgetcsv($fh);
}
fclose($fh);
You can use list
array("example.fr, 2013-08-24, test")
list($var1, $var2, $var3) = explode(', ', $array[0]); // or current
Unless I'm misunderstanding you, you can access the array elements and assign them to variables like this:
$var1 = $arrayName[0][0];
$var2 = $arrayName[0][1];
$var3 = $arrayName[0][2];
I can't tell from you're question if the array is holding a single string per index or if it is a 2D array. If it's holding strings then see realshadow's answer.
Use explode on every item of the array: http://www.w3schools.com/php/func_string_explode.asp
I don't think your syntax is quite right to create a multidimensional array, consider this example:
$myArray = array( array("example.fr", "2013-08-24", "test"),
array("toto.com, "2014-10-01", "test2"));
Now you have an array of arrays and can iterate over each.
If you know for sure how many items you have in each array then you can explode the array into its constituents, but if you don't know before hand than iterating will see you through.
I am not very sure with the structure, but let me know if this is what ur looking for, happy to help u then -
<?php
$myarr = array( array("example.fr", "2013-08-24", "test"),array("toto.com", "2014-10-01", "test2"));
foreach($myarr as $breakpart)
{
echo "<pre>";
print_r($breakpart);
}
OUTPUT -
Array
(
[0] => example.fr
[1] => 2013-08-24
[2] => test
)
Array
(
[0] => toto.com
[1] => 2014-10-01
[2] => test2
)
Codepad Link - codepad.org/6S7EMldq
I have an array like:
Array (
[0] => Array (
[A] => khaja.ghc#cdc.com
)
[1] => Array (
[A] => bag#example.com
)
)
Is there any easy process to store khaja.ghc#cdc.com and bag#example.com in an array in php? If so please help me.
I am doing this by foreach() method and after getting element I stored them in an array. Then finally by array_push() method I got the required array. But I think I missed easy process. Can you help me .
You still can use foreach modifing the value. Try
foreach($array as $key => &$value) {
if(is_array($value) && isset($value['A'])) $value = $value['A'];
}
and your $array will look like you want it to look.
If I understand well your question:
$data = array(array('A' => 'khaja.ghc#cdc.com'), array('A' => 'bag#example.com'));
$result = array();
foreach($data as $element)
if (is_array($element) && isset($element['A']))
$result[] = $element['A'];
print_r($result);
If you want to save a couple lines of code you can use array_map and create_function:
$a = array(array('A' => 'khaja.ghc#cdc.com'), array('A' => 'bag#example.com'));
$result = array_map(create_function('$x','$y = array_values($x); return $y[0];'), $a))
Although the saving on the number of code lines, I don't encourage you to take this approach. The code will be much easier to read and understand with a simple foreach loop.
I am fairly new to php and got this from a stack overflow question and cant seem to get it to work for me.
<?php
if (($handle = fopen("fullbox.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
echo "<pre>".print_r($data)." <br /></pre>";
}
fclose($handle);
}
echo $data[1];
?>
I need to set up a couple arrays for pricing using a large number of products(which I can pull from my csv file) Fullbox.csv consists of just 10 numbers with 2 decial places. I have just been trying to test this and this is the output that I get:
Array
(
[0] => 8.53
)
Array
(
[0] => 4.74
)
Array
(
[0] => 5.00
)
Array
(
[0] => 2.50
)
Array
(
[0] => 6.48
)
Array
(
[0] => 3.99
)
Array
(
[0] => 8.53
)
Array
(
[0] => 4.74
)
Array
(
[0] => 8.53
)
Array
(
[0] => 4.74
)
Why is the array setting all values in the [0} place holder of the array and also why is there a 1 in between each line. Thanks in advance.
Update If this is a ten item array this should then return the value of the 1 entry in the array but it doesn't. I essentially just need to store all of the prices so I can use them as variables later. I don't need them to be printed. Thanks again.
echo $data[1];
print_r does not return the formatted array by default; it outputs it and returns 1. Pass true as a second parameter.
echo "<pre>".print_r($data, true)." <br /></pre>";
All the values are in the 0 index of the array because arrays start at 0. There is nothing wrong there.
Try this:
$f = fopen(yourfile, "r");
$fs = filesize(yourfile);
$content = fread($f, $fs);
$lines = explode("\n", $content);
$result = array();
foreach($lines as $line) $result[] = explode(",", $line);
CSV as in Comma Seperated-Values is an array each line. So each line -even if it has only 1 value- is array.
Also you don't need to echo "print_r".
you also read the data from the CSV using the following function and sort using the usort() function.
http://www.pearlbells.co.uk/how-to-sort-a1a2-z9z10aa1aa2-az9az10-using-php/
Read data from the CSV
function readCSV() {
$csv = array_map('str_getcsv', file('data.csv'));
array_shift($csv); //remove headers
$csvData = splitandSort($csv);
createCSV($csvData);
}