Ignore empty cells PHPExcel - php

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.

Related

Function to return a associative array in php from another array

I am new in learning php and array . I have to create an associative array from another array . In addition The array must be returned in alphabetical order based upon the key names.
this is the input array
$customerTransactions = [
'bill=9898',
'bob=772',
'james=2672',
'jim=9872',
'luke=2665',
'jim=10000'
];
The output array should be like
$outputarray = [
'bill' => 9898,
'bob' => 772,
'james' => 2672,
'jim' => 19872,
'luke' => 2665
],
I am trying to create a function which will return the output array .
public function getCustomerBalances($customerTransactions)
{
$max = sizeof($customerTransactions);
$str = implode(",", $customerTransactions);
$outputarray = print_r (explode("=",$str));
return array($outputarray);
}
But result of this array is this this
Array(
[0] => bill
[1] => 9898,bob
[2] => 772,james
[3] => 2672,jim
[4] => 9872,luke
[5] => 2665,jim
[6] => 10000)
What can I do to correct it
You want to use explode not implode.
Below I have looped through your array of strings and explode each of the values in the array by the equals operator to get a new array that holds both the customer name and the transaction ID.
I am then populating a new array called $data with the results from this explosion, the first element in the $result array is the customer name, and the second element is the transaction ID.
Once you've got the array outputing correctly, you mentioned you wanted to order them alphabetically, to do this you would use ksort().
This is simple enough, you'd just need to call this function on the output array like so:
ksort($data);
This should work for you:
public function getCustomerBalances($transactions) {
$data = [];
foreach($transactions as $v) {
$result = explode('=', $v);
$data[$result[0]] = $result[1];
}
ksort($data);
return $data;
}

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'.

Import CSV file into array

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,

php array value repeated for each key

I have an multidimensional array made from database query and is like that:
Array
(
[0] => Array
(
[0] => -8.63296022565696
[x] => -8.63296022565696
[1] => 41.1584289069069
[y] => 41.1584289069069
[2] => 0
[seq] => 0
[3] => 2
[seq2] => 2
[4] => -8.63306031211831
[next_x] => -8.63306031211831
[5] => 41.1584543235506
[next_y] => 41.1584543235506
[6] => -8.64195115878864
[alert_x] => -8.64195115878864
[7] => 41.1599295066425
[alert_y] => 41.1599295066425
[8] => 54e728edafac1
[route] => 54e728edafac1
[9] => 54e728edafac1
[routeid] => 54e728edafac1
[10] => 2
[counttargetinter] => 2
[11] => passeio
[type] => passeio
[12] => 1355
[arcid] => 1355
)
All the values are repeated because have a key number and a key name.
Example: The value '-8.63296022565696' are in key "0" and "X".
How I can remove the duplicated?
This is how i made the array:
$query = "SELECT * FROM foo;";
$startRows = pg_query($connection, $query);
$startInfo = array();
while($list = pg_fetch_array($startRows)) {
$startInfo[] = $list;
}
Of course you can't mess with the generate JSON string to deal with the dups. You solve it during the creation of the array itself before encoding. Looking at the structure, this seems to be the problem of fetching both numeric and column indices.
Since you haven't posted any codes related to actually creating this JSON string, just use this basic idea on how to get rid of them.
If you intent do remove those numeric indices, you'll probably need to use fetch_assoc() flavours of your database API, so that in turn, you'll only get the column name indices instead of having them both.
Here's the idea:
$data = array(); // initialization of the container
while($row = your_fetch_assoc($result)) { // use assoc() instead to exclude those numeric indices
$data[] = $row;
}
echo json_encode($data);
Depending on what API you're using, if its PDO, either use -->fetch(PDO::FETCH_ASSOC) or just ->fetchAll(PDO::FETCH_ASSOC) without the need of a loop. If its MySQLi, then just use ->fetch_assoc()
EDIT: At last your codes, as I have suspected you're using _array() function which results associative and numeric indexed rows.
$query = "SELECT * FROM foo;";
$startRows = pg_query($connection, $query);
$startInfo = array();
while($list = pg_fetch_assoc($startRows)) {
$startInfo[] = $list;
}
Use pg_fetch_assoc() instead of _array() so that you'll get the associative indices only.
Like Ghost:
You can use pg_fetch_row() to get numeric indices or pg_fetch_assoc() to get field name.
$query = "SELECT * FROM foo;";
$startRows = pg_query($connection, $query);
$startInfo = array();
while($list = pg_fetch_row($startRows)) {
$startInfo[] = $list;
}
Try this:
foreach($walkroute as $routepoints){
foreach($routepoints as $key => $value){
if (is_int($key)){
unset($routepoints[$key]);
}
}
}
You have to modify it due to the fact that i don't know, what the structure and names of your array actually are.

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

Categories