Import CSV file into array - php

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,

Related

Loop not working with assosiative array Php

Can i make multidimensionalarrry to assosiative array, Right now i am getting following result
Array
(
[0] => Array
(
[id] => 1
[minimum_marks] => 55
[maximum_marks] => 65
)
[1] => Array
(
[id] => 2
[minimum_marks] => 44
[maximum_marks] => 70
}
)
I just want to put all values in single, i want result like following array
Array
(
[id] => 1
[minimum_marks] => 55
[maximum_marks] => 65
)
Array
(
[id] => 2
[minimum_marks] => 44
[maximum_marks] => 70
)
Here is my code,My code not showing only one record with loop (code should showing all minimum_marks and maximum_marks), where i am wrong ?
$result = $query->result_array();
$simpleArray = [];
foreach ($result as $skuArray) {
$simpleArray['minimum_marks'] = $skuArray['minimum_marks'];
$simpleArray['maximum_marks'] = $skuArray['maximum_marks'];
}
print_R($simpleArray);
I don't know why are you expecting this output. But my suggestion, if you want it really?
$simpleArray = [];
foreach ($result as $skuArray) {
$simpleArray['minimum_marks'] = $skuArray['minimum_marks'];
$simpleArray['maximum_marks'] = $skuArray['maximum_marks'];
print_R($simpleArray);
}
Print the value inside loop, so it wont push and it wont create multiple array. every time, it will overwrite. But please be sure, finally you get last array value only on the simpleArray. Hope you understood!
Let me explain with example. If you want to display the marks in table, I will suggest you to return directly like below instead of creating variable and retrieving it again.
echo '<table>
<tr><th>Min Marks</th><th>Max Marks</th></tr>';
foreach ($result as $skuArray) {
$minMarks = $skuArray['minimum_marks'];
$maxMarks = $skuArray['maximum_marks'];
echo '<tr><td>'.$minMarks.'</td><td>'.$minMarks.'</td></tr>';
}
echo '</table>';
I don't really understand what you want.
If you want to get your array in two different variables you can try this:
Use dynamic variables, the name of the variable is dynamically generated in your loop.
foreach($result as $key => $_array){
//$key is your inder of you multidimensional
$name_variable = '_array_number_'.$key; //Name of the variable
$$name_variable = $_array; //Instanciate dynamic variable
}
//You got now this two array
print_r($_array_number_0);
print_r($_array_number_1);
But please be more precise next time with what you expect and why you need this.
By the way, what happened to your code is that in the first loop you instanciate 'minimum_marks' and 'maximum_marks' in $_simple_array.
But in your second loop you overwrite the value of 'minimum_marks' and 'maximum_marks'.

multidimensional irregular array to CSV in PHP

First of all I know there are many threads dedicated to this topic but I didn't found/figured out the right solution for my problem, sorry if I missed something.
So I got an array that looks like this:
Array
(
[0] => id1
[1] => Array
(
[0] => Url1
)
[2] => id2
[3] => no url found
[4] => id3
[5] => Array
(
[0] => url3.1
[1] => url3.2
[2] => url3.3
)
)
and i want to build a csv looking like:
id1,url1
id2,no url found
id3,url3.1,url3.2,url3.3
tried with
foreach($array as $row){
fputcsv($csv, $row, ',');
}
but it grabs only the elements of the subarrays if they exist. How should I approach that? Thanks in advance!
I would suggest creating an intermediate array from the original one, which would have the desired structure, and then create the CSV output from that:
// Preprocess the array to get the format needed for the CSV output
for ($i = 0; $i < count($array); $i += 2) {
$result[] = is_array($array[$i+1])
? array_merge([$array[$i]], $array[$i+1])
: [$array[$i], $array[$i+1]];
}
foreach($result as $row){
fputcsv($csv, $row, ',');
}
See it run on eval.in.

How to pull specific key values from array inside array

I have array output like below,
Array ( [0] => Array ( [file_name] => test.pdf
[file_type] => application/pdf
[file_path] => /Applications/AMPPS/www/testing/uploads/attachments/2/
[1] => Array ( [file_name] => test1.pdf
[file_type] => application/pdf
[file_path] => /Applications/AMPPS/www/testing/uploads/attachments/2/ )
How can i pull a new array like below
Array( [0] => test.pdf [1] => test1.pdf)
Background,
I am doing multiple file upload using Codeigniter, my files are uploading and getting return data array, i want only file names to be send back to my view, so need to pull file names of files which are uploaded,
Any suggestions, hints?
Thanks,
Use array_column() like,
$new_array = array_column ($your_array, 'file_name');
If using PHP version < 5.5, refer this
<?php
$arrResult = array();
foreach ($arrGiven as $key => $value) {
$arrResult[] = $value['file_name'];
}
$arrGiven is the first array from which you want to extract the data. $arrResult will contain the data like you wanted.
$new = array();
foreach($old as $entrie){
$new[] = $entrie['file_name'];
}
This will go through all the entreis of the old array, and put the file_name of each in a new array.
Simply do this
$files = array();
foreach ($array as $key => $value) {
$files[] = $array[$key]['file_name'];
}
print_r($files);

PHP rewriting a json array (Undefined offset)

I'm taking some json, made by OpenLibrary.org, and remake a new array from the info.
Link to the OpenLibrary json
here is my PHP code to decode the json:
$barcode = "9781599953540";
function parseInfo($barcode) {
$url = "http://openlibrary.org/api/books?bibkeys=ISBN:" . $barcode . "&jscmd=data&format=json";
$contents = file_get_contents($url);
$json = json_decode($contents, true);
return $json;
}
the new array I'm trying to make looks something like this:
$newJsonArray = array($barcode, $isbn13, $isbn10, $openLibrary, $title, $subTitle, $publishData, $pagination, $author0, $author1, $author2, $author3, $imageLarge, $imageMedium, $imageSmall);
but when I try to get the ISBN_13 to save it to $isbn13, I get an error:
Notice: Undefined offset: 0 in ... on line 38
// Line 38
$isbn13 = $array[0]['identifiers']['isbn_13'];
And even if I try $array[1] ,[2], [3].... I get the same thing. What am I doning wrong here! O I know my Valuable names might not be the same, that's because they are in different functions.
Thanks for your help.
Your array is not indexed by integers, it is indexed by ISBN numbers:
Array
(
// This is the first level of array key!
[ISBN:9781599953540] => Array
(
[publishers] => Array
(
[0] => Array
(
[name] => Center Street
)
)
[pagination] => 376 p.
[subtitle] => the books of mortals
[title] => Forbidden
[url] => http://openlibrary.org/books/OL24997280M/Forbidden
[identifiers] => Array
(
[isbn_13] => Array
(
[0] => 9781599953540
)
[openlibrary] => Array
(
[0] => OL24997280M
)
So, you need to call it by the first ISBN, and the key isbn_13 is itself an array which you must access by element:
// Gets the first isbn_13 for this item:
$isbn13 = $array['ISBN:9781599953540']['identifiers']['isbn_13'][0];
Or if you need a loop over many of them:
foreach ($array as $isbn => $values) {
$current_isbn13 = $values['identifiers']['isbn_13'][0];
}
If you expect only one each time and must be able to get its key without knowing it ahead of time but don't want a loop, you can use array_keys():
// Get all ISBN keys:
$isbn_keys = array_keys($array);
// Pull the first one:
$your_item = $isbn_keys[0];
// And use it as your index to $array
$isbn13 = $array[$your_item]['identifiers']['isbn_13'][0];
If you have PHP 5.4, you can skip a step via array dereferencing!:
// PHP >= 5.4 only
$your_item = array_keys($array)[0];
$isbn13 = $array[$your_item]['identifiers']['isbn_13'][0];

php csv to array

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

Categories