PHPExcel, If $value = $value then skip? - php

I'm trying to read a xlsx file using PHPExcel, however I got a problem trying to generate a navbar using column 1 values. Since Most of my column contains same type of value e.g. T-Shirt, T-Shirt... Cap, Cap, Cap.. Hoodies, Hoodies...
I got a problem filtering out the same value, does someone has any idea how to skip the same value as previous one?
Here's my code:
<?php
for ($column = 2; $column <= $highestRow; ++$column) {
$cat = $objWorksheet->getCellByColumnAndRow(0, $column)->getValue();
if ($cat == $cat) {
continue;
} else {
echo '<li>'.$cat.'</li>';
}
}
?>
Would be great if it works under <li></li> for my navbar

Try this.
//Get the value of $column -1 aka the previous column.
$previousColumn = $objWorksheet->getCellByColumnAndRow(0, $column - 1)->getValue();
$cat = $objWorksheet->getCellByColumnAndRow(0, $column)->getValue();
if ($cat == $previousColumn) {
continue;
} else {
echo '<li>'.$cat.'</li>';
}

Related

How to fix Array overwritten after foreach loop php

I am having issue data Array overwritten in foreach loop. Result I am getting like this wrongRight together .Right answer is showing but also wrong for example ZucchiniCauliflower.Please help
CODE 1
$data = array();
$dis_07= null;
$dis_03 = null;
if (is_array($row)) {
foreach ($row as $value) {
$gccat_id = $value->gccat_id;
$ccat_id = $value->ccat_id;
$cat = $value->cat_id;
if (isset($gccat_id) && $gccat_id == $id) {
$dis_07 = $value->category;
$dis_02 = $value->child_id;
}
if (isset($ccat_id) && $ccat_id == $id) {
$dis_03 = $value->category;
$dis_02 = $value->parent_id;
}
}
}
$data['Dis_03'] = $dis_03;
$data['Dis_07'] = $dis_07;
if (isset($data['Dis_03'])) {
echo $data['Dis_03'];
}
if (isset($data['Dis_07'])) {
echo $data['Dis_07'];
}
First I tried this way But In one I was getting right in second link I am getting right So Tried the code previous one .In the prvious I am getting correct and wrong one together EExample ZucchiniCauliflower
CODE 2
if (isset($id)) {
$db = Database::newInstance();
$data = array();
$data['cat_status'] = 1;
$sql = "SELECT * FROM category WHERE cat_status=:cat_status ";
$row = $db->read($sql,$data);
$data['id'] = $crypt->decryptId($id);
echo $data['id'];
$id=$data['id'];
if (is_array($row)) {
foreach ($row as $value) {
$gccat_id=$value->gccat_id;
$ccat_id = $value->ccat_id;
$cat = $value->cat_id;
if (isset($gccat_id) && $gccat_id == $id) {
$data['Dis_03']=$value->category;
}
if (isset($ccat_id) && $ccat_id == $id) {
$data['Dis_03'] = $value->category;
break;
}
}
}
}
--------------------------READ FROM HERE------------------------
Here is a link one when I click on this link
$id=$value11->gccat_id;
$title
I expected the output is
Home>Raspberry
Here is a link Second link when I click on this link
Here id is ($value11->gccat_id)
window.open('<?= BASEURL ?>ap/'+id,'_self');
I expected the output is
Home>Cauliflower
1. WHEN I Use the Code 2 (Added break in this condition
(isset($ccat_id) && $ccat_id == $id)) Then click on link second
it gives output Home>Cauliflower which I was expecting. It is
correct.
2. But this time as I added the break in (isset($ccat_id) && $ccat_id == $id). I click on link one It gives wrong output which I was not expecting. Home>Squash which is wrong.
In one link I was expecting
Home>Cauliflower
ERROR NOTE If I add Break; then link Second gives correct output but when I remove Break; then link one give correct. I wanted Both link should give correct output.
Problem was with cat_id,ccat_id ,gccat_id.
I provided 8 digit unique number with the following output,now I am getting the correct output.
function generateUniqueNumber() {
return sprintf('%08d', mt_rand(1, 99999999));
}

PHP if condition: Logical operators for filter from a form

I'm working with a form using the <datalist> tag, I have two input tags getting information from two different arrays. Below the form there is a Kanban board, the objective of the form is to serve as a filter, so when a user fills any of the inputs (or both) the board with fill accordingly.
Here is the problem: I had made two if staments (one for input) that work great when I use them alone but that I don't know how to put together because I don't know how to check which of the inputs has been filled (for that I believe I may have to use the issset() function), then if only one of them is used I need to use the || logical operator between them but if both are filled I need to use the && operator.
Using this condition (|| logical operator):
if (($tasksArray[$i]["responsible-party-names"] == $_POST['members'] && isset($_POST['members'])) ||
(($tasksArray[$i]['project-name'] == $_POST['projects'] && isset($_POST['projects']))))
If I fill only the members input it returns what it should.
If I fill only the projects input it returns all the projects in the array (although when using the if condition without the left part it works well).
Finally, if I fill both inputs I get the right project but all the team members.
What would be the simplest way to get it right?
Update:
This if condition it's inside the moveArray function, what comes after the if block looks like this:
{
$task = '<div id="item'.$i.'"'.'draggable="true" class="c-drag">';
$task .= '<div class="card cardTitle">'.$tasksArray[$i]['content'].'</div>';
$task .= '<div class="card cardDescription">'.$tasksArray[$i]['description'].'</div>';
$task .= '<div class="card cardProjectName">'.$tasksArray[$i]['project-name'].'</div>';
if (isset($tasksArray[$i]["responsible-party-names"])) {
$task .= '<div class="card cardProjectResponsibleName">'.$tasksArray[$i]['responsible-party-names'].'</div>';
} else {
$task .= '<div class="card cardProjectResponsibleName">'."Anyone".'</div>';
}
if ($tasksArray[$i]["due-date"] != "") {
$task .= '<div class="card cardDueDate">'.date("d/m/Y", strtotime($tasksArray[$i]["due-date"])).'</div>';
}
$task .= '</div>';
return $task;
}
Then I call the function on every part of the board (unassigned, to do, in progress, finished)
echo '<div id="board">';
echo '<div id="unassing">';
echo '<div id="unassing-bg" class="title">Unassigned</div>';
for ($i=0; $i < $tasksLenght; $i++) {
if (isset($tasksArray[$i]['boardColumn']) === false) {
echo(moveArray($i, $tasksArray));
}
}
echo '</div>';
echo '<div id="todo">';
echo '<div id="todo-bg" class="title">To Do</div>';
for ($i=0; $i < $tasksLenght; $i++) {
if (isset($tasksArray[$i]['boardColumn']) && $tasksArray[$i]['boardColumn']['id'] == "9805") {
echo(moveArray($i, $tasksArray));
}
}
echo '</div>';
echo '</div>';
And that produce sort of "a card" with data about a task in the corresponding place of the board.
You actually need the isset to come before trying to access the key on $_POST to prevent the "undefined" error.
I am assuming you have some code that looks like this:
$matchingTasks = [];
for ($i=0; $i <= count($tasksArray); $i++) {
...
}
return $matchingTasks; // or something
If that is the case, what you want is more like this:
matchingTasks = [];
foreach ($tasksArray as $task) {
// Store your search values
$members = isset($_POST['members']) ? $_POST['members'] : false;
$projects = isset($_POST['projects']) ? $_POST['projects'] : false;
// Store the search matches, only if you are searching by that key
$members_match = $members && $task["responsible-party-names"] == $members;
$projects_match = $projects && $task['project-name'] == $projects;
// if you are searching for BOTH must match BOTH
if ($members && $projects)
if ($members_match && $projects_match) {
$matchingTasks[] = $task;
}
continue;
}
// if you are searching for EITHER can match EITHER
if ($members XOR $projects) {
if ($members_match || $projects_match) {
$matchingTasks[] = $task;
}
continue;
}
// if you are not searching match ALL
$matchingTasks[] = $task;
}
return $matchingTasks;
More advanced, and would allow for more customization, is to stack these in a filter pattern like this:
$members = isset($_POST['members']) ? $_POST['members'] : false;
$projects = isset($_POST['projects']) ? $_POST['projects'] : false;
if ($members)
$tasksArray = filter_by_members($tasksArray, $members);
if ($projects)
$tasksArray = filter_by_project($tasksArray, $projects);
return $tasksArray;
//... elsewhere
function filter_by_members($tasks, $members) {
$result = [];
foreach ($tasks as $t) {
if ($task["responsible-party-names"] == $members) {
$result[] = $task;
}
}
return $tasks;
}
function filter_by_project($tasks, $project) {
$result = [];
foreach ($tasks as $t) {
if ($task["project-name"] == $project) {
$result[] = $task;
}
}
return $tasks;
}
This would let you stack new search filters, like filter_by_id or filter_by_date and by defining filter functions you can stack as many as you like without getting crazy with the logic.

Laravel Trying to Get property of non object (from eloquent model)

Already read some of questions about this problem on stackoverflow and none of that answers apply to me.
When I run:
$item_price = ItemPrice::where('item_name',$itemname)->first();
and then
$item_price->price
I get Trying to get property of non-object but when I run:
dd($item_price = ItemPrice::where('item_name',$itemname)->first());
It's returning object with attributes name, price etc. I don't really understand what is happening here.
Full code:
foreach ($inventorydecoded->assets as $asset) {
$i = 0;
$a = 0;
while ($a < 1) {
if ($inventorydecoded->descriptions[$i]->classid == $asset->classid) {
$a = 1;
$classid = $inventorydecoded->descriptions[$i]->classid;
$itemname = $inventorydecoded->descriptions[$i]->market_hash_name;
$tradable = $inventorydecoded->descriptions[$i]->tradable;
$name_color = $inventorydecoded->descriptions[$i]->name_color;
;
}
$i++;
} // end of while
if ($tradable === 1 && strpos_arr($itemname, $blacklist) == false ) {
$item_price = ItemPrice::whereItemName($itemname)->first();
// dd(ItemPrice::where('item_name',$itemname)->first());
$items[] = ['assetid' => $asset->assetid,'classid'=> $classid,'itemname'=>$itemname,'name_color'=>$name_color,'price'=> $item_price->price];
$serialized_inventory = serialize($items);
}
} // end of foreach
You're using this query in loop, so one of those is empty and returns null. So you need to do simple check:
if (is_null($item_price)) {
// There is no price for this item, do something.
}
Try this:
$item_price = ItemPrice::whereItemName($itemname)->first();

PHPExcel - Finding First Column With blank cell

Trying to locate the first blank cell in a column. The idea is to pick a column that I know has to have a value (in this case, JOB_NUMBER) and scan through it until a blank cell is found. The code below, in my mind, should do that. However, it never stops. I imagine it is stuck in the while loop, but I don't understand why.
Code:
<?php
require('./Classes/PHPExcel/IOFactory.php');
ini_set('max_execution_time', 800);
ini_set('memory_limit', 2000000000);
$inputFileType = 'Excel2007';
$inputFileName = $_FILES['file']['tmp_name'];
class MyReadFilter implements PHPExcel_Reader_IReadFilter {
public function __construct($fromColumn, $toColumn) {
$this->columns = array();
$toColumn++;
while ($fromColumn !== $toColumn) {
$this->columns[] = $fromColumn++;
}
}
public function readCell($column, $row, $worksheetName = '') {
// Read columns from 'A' to 'AF'
if (in_array($column, $this->columns)) {
return true;
}
return false;
}
}
$filterSubset = new MyReadFilter('A', 'AF');
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objReader->setReadFilter($filterSubset);
$objReader->setLoadSheetsOnly( array("NORTH") );
$objPHPExcelReader = $objReader->load($inputFileName);
$r = 3500;
while(isset($maxrow_north) != 1){
$cellvalue = $objPHPExcelReader->getSheetByName('NORTH')->getCellByColumnAndRow(2, $r);
if(isset($cellvalue) != 1){
$maxrow_north = $r;
} elseif($r > 4000) {
echo "It's over 4000!";
} else {
$r = $r++;
}
}
echo $maxrow_north;
?>
Some more background
I am having admins upload .xlsx .xls or .csv files into an html form. The code, above, is the handler. I have limited the number of columns seen because the original creator of the .xlsx file thought it would be a great idea to have the columns go all the way out to XCF.
The rows also go all the way out to somewhere around 10,000. So, I want to find the first blank row and stop there.
TIA!
Don't use
if(isset($cellvalue) != 1){
A cell value always exists even if it's an empty string or a null: and you're not testing the actual cell value, but the existence of a cell.... simply get() ting a cell will create a new empty cell object if one didn't already exist
You need to test the actual value stored in the cell
if($cellvalue->getValue() === NULL || $cellvalue->getValue() === '') {
$maxrow_north = $r;
And if you're trying to find the first blank cell in the column, then break once you've found it rather than carry on iterating till you reach your max
(Note, doesn't check for rich text in cells)
EDIT
Example, that also allows for merged cells
function testInMergeRangeNotParent($objWorksheet, $cell)
{
$inMergeRange = false;
foreach($objWorksheet->getMergeCells() as $mergeRange) {
if ($cell->isInRange($mergeRange)) {
$range = PHPExcel_Cell::splitRange($mergeRange);
list($startCell) = $range[0];
if ($cell->getCoordinate() !== $startCell) {
$inMergeRange = true;
}
break;
}
}
return $inMergeRange;
}
$column = 2; // Column to check
$max = 4000;
echo 'Get First blank row in column ', $column, PHP_EOL;
$r = 3500; // Starting row
while(true){
$cell = $objPHPExcelReader->getSheetByName('NORTH')->getCellByColumnAndRow($column, $r);
if ($cell->getValue() === NULL &&
!testInMergeRangeNotParent($objPHPExcelReader->getSheetByName('NORTH'), $cell)) {
break;
}elseif($r > $max) {
echo "It's over $max !";
break;
}
$r++;
}
echo 'First blank row in column ', $column, ' is ', $r, PHP_EOL;

Page Headings and Functions with their headings

I have one more question for the day. I'm trying to make my biography page totally customizable for my custom CMS project I'm doing. If you notice in the view I have 3 h2 tags for Quotes, Allies, Rivals. What I would like to do is put the h3's into my db and then have it do a foreach loop for each one of them so I'm thinking some how I"m going to have to store the function that goes with the pageheading that way it doesn't have to run it if its not active on the page. I know this can be easily done however there's too much for me to focus on what I need to do in order to complete this. Keep in mind that depending on which page you are in the bio will impact which headings will be available.
As of right now here is my controller:
$activeTemplate = $this->sitemodel->getTemplate();
$footerLinks = $this->sitemodel->getFooterNav();
$bodyContent = "bio";//which view file
$bodyType = "main";//type of template
$this->data['activeTemplate'] = $activeTemplate;
$this->data['footerLinks']= $footerLinks;
$this->load->model('biomodel');
if($character !== "jfkdlsjl")
{
if((!empty($character))||(!isset($character))||(trim($character) !== '')||($character !== NULL))
{
$bioArray = $this->biomodel->getCharacterBio($character);
if ($bioArray == "empty")
{
$this->data['bioArray']= array();
}
else
{
if (($bioArray[0]->characters_statuses_id == 2)||($bioArray[0]->characters_statuses_id == 3)||($bioArray[0]->characters_statuses_id == 5))
{
$this->data['bioArray']= array();
}
else
{
$this->data['bioArray']= $bioArray;
$bioPagesArray = $this->biomodel->getBioPages();
$alliesArray = $this->biomodel->getCharacterAllies($bioArray[0]->id);
$rivalsArray = $this->biomodel->getCharacterRivals($bioArray[0]->id);
$quotesArray = $this->biomodel->getCharacterQuotes($bioArray[0]->id);
$this->data['bioPagesArray']= $bioPagesArray;
$this->data['alliesArray']= $alliesArray;
$this->data['rivalsArray']= $rivalsArray;
$this->data['quotesArray']= $quotesArray;
}
}
}
}
And here is my view:
echo "<h2>Quotes</h2>";
if (!empty($quotesArray))
{
echo "<ul>";
for($x = 0; $x <= (count($quotesArray)-1); $x++)
{
echo "<li>".stripslashes($quotesArray[$x]->quote)."</li>";
}
echo "</ul>";
}
echo "<h2>Allies</h2>";
if (!empty($alliesArray))
{
echo "<ul>";
foreach ($alliesArray as $row)
{
echo "<li>".stripslashes($row)."</li>";
}
echo "</ul>";
}
echo "<h2>Rivals</h2>";
if (!empty($rivalsArray))
{
echo "<ul>";
foreach ($rivalsArray as $row)
{
echo "<li>".stripslashes($row)."</li>";
}
echo "</ul>";
}
I don't know what you mean about storing the function nor which function you don't want to run.
Assuming we're working with the last else statement in your controller
$alliesArray = $this->biomodel->getCharacterAllies($bioArray[0]->id);
$rivalsArray = $this->biomodel->getCharacterRivals($bioArray[0]->id);
$quotesArray = $this->biomodel->getCharacterQuotes($bioArray[0]->id);
... and the function you "don't want to run" is the foreach loop on the array in the view, just handle the logic in your view:
if(($this->uri->segment(n)=='pageIwantQuotesOn') && (!empty($quotesArray)){
echo "<h2>Quotes</h2>";
echo "<ul>";
for($x = 0; $x <= (count($quotesArray)-1); $x++)
{
echo "<li>".stripslashes($quotesArray[$x]->quote)."</li>";
}
echo "</ul>";
}
...

Categories