I currently have a query that returns the array below.. When I try to export the data to a CSV file I see the data twice (The columns are repeted, not the rows).. Can someone explain to my why? (I want to have each records show only once)
Array
(
[0] => Array
(
[0] => 6991
[id] => 6991
[1] => 8588
[work_num] => 8588
[2] => Test123
[name] => Test123
[3] => 1407154
[deployed] => 1407154
[4] => 2015-10-13
[created_date] => 2015-10-13
)
)
This is the code that I am using to export the data
// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');
// output the column headings
fputcsv($output, array('id','Work Number','Name','Deployed','Date'));
$get_data = $CLASSNAME->FuntionName(Parameters);
foreach($get_data as $data_row) {
fputcsv($output, $data_row);
}
fclose($output);
If you are using MySQL, then replace mysql_fetch_array to mysql_fetch_row.
mysql_fetch_array returns result set as both numeric and associative array.
mysql_fetch_row will return result set as only numeric array.
Either fix your incoming data (when using PDO, use PDO::FETCH_ASSOC or PDO::FETCH_NUM instead of PDO::FETCH_BOTH, which is default) or name your columns when putting to csv:
foreach($get_data as $data_row) {
fputcsv($output, array(
$data_row['id'],
$data_row['work_num'],
$data_row['name'],
$data_row['deployed'],
$data_row['created_date']
));
}
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 create simple function to check if table exists in the database or not ..
I want fetch all table in the database and i use like
$sql = "SHOW TABLES FROM plus LIKE '%group%'";
$do = mysqli_query($db,$sql);
$table = array();
while ($row = mysqli_fetch_row($do)) {
$table[] = $row ;
}
print_r($table);
}
the output
Array ( [0] => Array ( [0] => group_1 ) [1] => Array ( [0] => group_2 ) [2] => Array ( [0] => group_3 ) [3] => Array ( [0] => group_4 ) )
I want all table in one array to encode with Json ,
and use the array to check in_array by PHP ..
==Edited==
I'm getting JSON as
[["group_1"],["group_2"],["group_3"],["group_4"]]
But, I'm expecting
["group_1","group_2","group_3","group_4"]
You could use json_encode, to get your resultset as json
echo json_encode($table);
Since, you are getting sub-array with your $table array, you need to merge them into single array to get your expected output.
You could make changes to your loop.
while ($row = mysqli_fetch_row($do)) {
array_merge($table,$row);
}
echo json_encode($table);
or, to print array
var_dump($table);
Array
(
[0] => Array
(
[acctcode] => 631
[description] => Blood Transfussion Set, Blood Transfusion Set- ADULT
[pchrgqty] => 1.00
[pchrgup] => 17.00
[pcchrgamt] => 17.00
[patlast] => GUADA�A
[patfirst] => FRITZIE ELINE
[patmiddle] => DAYTEC
[patsuffix] =>
)
)
The above array in php is result of print_r($result); now this array will be json_encoded as below:
echo json_encode($result, JSON_UNESCAPED_UNICODE);
I am encoding this because it is for ajax request. Now in echo part it is not returning anything. I dont know why this is happening but my guess is because of
“Ñ” which is in the [patlast] => GUADA�A and is shown as �. I am getting this result set in a select of MSSQL DATABASE.
How to handle this result set in MSSQL and be able to return the correct data.
I have found the best solution for my project in here
Using below code:
// Create an empty array for the encoded resultset
$rows = array();
// Loop over the db resultset and put encoded values into $rows
while($row = mysql_fetch_assoc($result)) {
$rows[] = array_map('utf8_encode', $row);
}
// Output $rows
echo json_encode($rows);
The answer was given my user Kemo
I need to send data to the client side in JSON format.
So far, it worked just fine with json_encode as follows:
$sql = "SELECT `card`.`CardID`,`card`.`Text`,... WHERE (`card`.`CardID`= :ItemId)";
$stmt = $dbh->prepare($sql);
$stmt->bindParam(':ItemId', $itemid);
$stmt->execute();
while ($row = $stmt->fetchObject()) {
$posts[]=$row;
}
...
...
$res["rows"] = $posts;
$res["maptel"] = $maptelindicator;
echo json_encode($res,JSON_UNESCAPED_UNICODE);
But now I have a problem. I have a new field (Videofiles) in the DB that is already JSON formatted- stored as the ouput of a SDK function. If I encode this JSON encoded field once more, I get data which is unreadable on the client side..
How can I json_encode all the other data, but skip this specific field, Videofiles?
Here is the output of a sample data structure using print_r:
Array
(
[rows] => Array
(
[0] => stdClass Object
(
[Name] => Company13
[CID] => 26
[CardID] => 26-000002
[Text] => Kleopatra Deluxe Hotel reservations
[ImageLink] =>
[VideoFiles] => [{"quality":"mobile","type":"video/mp4","width":480,"height":270....}]
[ClickDate] => 2015-11-03
)
)
[maptel] => 0
)
Thanks...
You could use json_decode to decode the already encoded field and then add the result in the $res array.
Best way to do it delete this section in SQL!
But if you want to delete in php it will have a cost for you and you can use unset for this situation;
foreach ($posts as $post){
unset($posts['VideoFiles']);
}
$res["rows"] = $posts;
$res["maptel"] = $maptelindicator;
echo json_encode($res,JSON_UNESCAPED_UNICODE);
I'm using the library PHPExcel to read data in an Excel file. The problem I'm having, is that when I use something like:
$obj = PHPExcel_IOFactory::load($file);
$data = $obj->getActiveSheet()->toArray(null,true,true,true);
To load my file and convert its content into an array, I get all the columns and rows of my Excel file in my array even those without any data in them. Is there a method or something in the library PHPExcel to tell it to ignore cells in my Excel sheet that do not contain any data? (Instead of having a bunch of empty associative arrays in my $data)
If your problem is in getting empty columns that go after real data, and you would like to avoid these, you could do something like this:
$maxCell = $sheet->getHighestRowAndColumn();
$data = $sheet->rangeToArray('A1:' . $maxCell['column'] . $maxCell['row']);
This will return array representing only the area containing real data.
I have this solution for my case
$maxCell = $objWorksheet->getHighestRowAndColumn();
$data = $objWorksheet->rangeToArray('A1:' . $maxCell['column'] . $maxCell['row']);
return all rows with all empty string as:
[1] => Array
(
[0] =>
[1] =>
[2] =>
[3] =>
[4] =>
[5] =>
[6] =>
[7] =>
[8] =>
[9] =>
[10] =>
[11] =>
[12] =>
[13] =>
)
To remove these empty rows
$data = array_map('array_filter', $data);
will return
[1] => Array
(
)
And this is the finale solution:
$maxCell = $objWorksheet->getHighestRowAndColumn();
$data = $objWorksheet->rangeToArray('A1:' . $maxCell['column'] . $maxCell['row']);
$data = array_map('array_filter', $data);
$data = array_filter($data);
will return an array with only filled rows .. hope that help
No there isn't. The toArray() method returns the first argument (NULL) to represent an empty cell. You can then apply standard PHP array functions such as array_filter() to eliminate empty cells.
foreach($data as $key => &$row) {
$row = array_filter($row,
function($cell) {
return !is_null($cell);
}
);
if (count($row) == 0) {
unset($data[$key]);
}
}
unset ($row);
This will eliminate every cell that is a NULL (empty) value, and every row that comprises nothing but empty cells. It will preserve the array keys, so your array keys will still give you a cell reference.
Note that an cell containing an empty string is not a null cell, so these will be retained, although the array_filter() callback could be modified to remove them as well.