if.. elseif statement working only on elseif - php

I have the below php script working if you use one condition (if..else works fine) If try to use if and else if statement( because of two conditions are true) the second one is working and not the first one.
Script:
$damage_topdir = "/ids_images/drsIN2/";
$damage_topdir1 = "/ids_images/drsIN1/";
$tmp = split(" ", $displayEntryDatetime);
$date = $tmp[0];
$time = $tmp[1];
$tmp = split("/", $date);
$day = $tmp[0];
$month = $tmp[1];
$year = $tmp[2];
$displayEntryDatetime = $year."-".$month."-".$day." ".$time;
$cam_list = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16);
if ($cam = 'DRHdrsIN1')
{
foreach ($cam_list as $cam) {
$timestamp = strtotime($displayEntryDatetime);
$cam_delta =6;
$timestamp = $timestamp - $cam_delta;
for ($i = 0; $i < $cam_delta+20; $i++) {
$cdate = date("d_m_Y* H_i_s", $timestamp);
$image_name = "/xampp/htdocs" . $damage_topdir. $cam . "/Cam*" . $cam . "*-" .$cdate . "*";
foreach (glob($image_name) as $filename) {
if (file_exists($filename)) {
$fs_image = str_replace("/xampp/htdocs", "", $filename);
print "<h3>Camera $cam</h3>";
print "<img src=\"$fs_image\" height=240 width=320 />\n";
}
}
$timestamp++;
}
}
}
elseif($cam = 'DRHdrsIN2') ----> this one executes normally...
{
foreach ($cam_list as $cam) {
$timestamp = strtotime($displayEntryDatetime);
$cam_delta = 6;
$timestamp = $timestamp - $cam_delta;
for ($i = 0; $i < $cam_delta+20; $i++) {
$cdate = date("d_m_Y* H_i_s", $timestamp);
$image_name = "/xampp/htdocs" . $damage_topdir1. $cam . "/Cam*" . $cam . "*-" .$cdate . "*";
foreach (glob($image_name) as $filename) {
if (file_exists($filename)) {
$fs_image = str_replace("/xampp/htdocs", "", $filename);
print "<h3>Camera $cam</h3>";
print "<img src=\"$fs_image\" height=240 width=320 />\n";
}
}
$timestamp++;
}
}
}
else {
}
?>

You ned to use a comparison, not an assignment:
if ($cam == 'DRHdrsIN1'){
....
elseif($cam == 'DRHdrsIN2'){
...

Related

Big SQL Select Query in Laravel

I have table lids with under 430k entries.
How can I do SELECT query faster, optimized because now this query working under 5-7 minutes.
Heard something about Eloquent chunk in Laravel, but need clear PHP solution or with DB object.
Maybe with 'for' construction to process 100-1000 entries at a time, smthng like this.
Tried to do 'for' construction, but don't know how to do this optimized.
Be gentle with me pls :)
Want to know your opinion.
How can i upgrade it?
UPD: Did something like this
$count = $db->doQuery("SELECT count(*) FROM `lids`"); // db - my custom object with Database connection
$count = $count[0]['count(*)'];
$hundreds = $count / 100; // get 'for' counts
$start = 43; // id index starts from 43 in the table
$end = 142;
for ($index = 1; $index < $hundreds; $index++) {
$leads = [];
$leads = $db->doQuery("SELECT * FROM `lids` WHERE `id` BETWEEN " . $start . " AND " . $end . "");
// var_dump($leads);
// die();
if (empty($leads)) {
$start += 100;
$end += 100;
continue;
}
$uniques = [];
foreach ($leads as $lead) {
if (empty($lead['json_vars'])) continue;
$vars = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $lead['json_vars']); // hot fix for charset, from DB comes string in utf8mb4
$json = json_decode($vars, true);
if (!isset($json['ser']['HTTP_COOKIE']) || !str_contains($json['ser']['HTTP_COOKIE'], '_fbc')) continue;
$lead['json_vars'] = $json['ser']['HTTP_COOKIE'];
// check for unique values
if (!isset($uniques[$lead['id']]) || $uniques[$lead['id']]['phone'] != $lead['phone']) {
$uniques[$lead['id']] = $lead;
}
}
foreach ($uniques as $unique) {
$lid = Lid::create($unique);
}
$start += 100;
$end += 100;
// here i get residue of entries
if ($hundreds - $index < 1) {
$leads = $db->doQuery("SELECT * FROM `lids` WHERE `id` IN(" . ($count - $hundreds * 100) . ", " . $count . ") AND WHERE ");
foreach ($leads as $lead) {
$json = json_decode(preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $lead['json_vars']), true);
if (!str_contains($json['ser']['HTTP_COOKIE'], '_fbc')) continue;
$lead['json_vars'] = $json['ser']['HTTP_COOKIE'];
$lid = Lid::create($lead);
}
}
}
Upd2:
$db = new Database();
$counter = 0;
$scriptStart = date('d.m.Y H:i:s', strtotime('now'));
$lastRemote = $db->lastId('lids');
$lastInner = Lid::all(['id'])->last();
$lastInner = $lastInner->id;
$count = $lastRemote - $lastInner;
if ($count < 0) {
echo 'no new objects, canceled';
return false;
}
$start = $lastInner + 1;
$end = $lastRemote;
$fewEntries = false;
if ($count < 500) {
$fewEntries = true;
$index = $lastInner;
$hundreds = $lastRemote;
} else {
$index = 1;
$hundreds = $count / 100;
$end = $start + 99;
}
if ($fewEntries) {
$leads = $db->itemsBetween('lids', 'id', [$start, $end]);
$uniques = [];
foreach ($leads as $lead) {
if (empty($lead['json_vars'])) continue;
$vars = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $lead['json_vars']);
$json = json_decode($vars, true);
if (!isset($json['ser']['HTTP_COOKIE']) || !str_contains($json['ser']['HTTP_COOKIE'], '_fbc')) continue;
$lead['json_vars'] = $json['ser']['HTTP_COOKIE'];
if (
!isset($uniques[$lead['id']]) ||
$uniques[$lead['id']]['phone'] != $lead['phone'] &&
$uniques[$lead['id']]['ip'] != $lead['ip'] &&
$uniques[$lead['id']]['request_link'] != $lead['request_link']
) {
$uniques[$lead['id']] = $lead;
}
}
foreach ($uniques as $unique) {
$lid = Lid::create($unique);
$counter++;
}
} else {
for ($index; $index < $hundreds; $index++) {
$leads = [];
$leads = $db->itemsBetween('lids', 'id', [$start, $end]);
// var_dump($leads);
// die();
$uniques = [];
foreach ($leads as $lead) {
if (empty($lead['json_vars'])) continue;
$vars = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $lead['json_vars']);
$json = json_decode($vars, true);
if (!isset($json['ser']['HTTP_COOKIE']) || !str_contains($json['ser']['HTTP_COOKIE'], '_fbc')) continue;
$lead['json_vars'] = $json['ser']['HTTP_COOKIE'];
if (
!isset($uniques[$lead['id']]) ||
$uniques[$lead['id']]['phone'] != $lead['phone'] &&
$uniques[$lead['id']]['ip'] != $lead['ip'] &&
$uniques[$lead['id']]['request_link'] != $lead['request_link']
) {
$uniques[$lead['id']] = $lead;
}
}
foreach ($uniques as $unique) {
$lid = Lid::create($unique);
$counter++;
}
$start += 100;
$end += 100;
}
}
$scriptEnd = date('d.m.Y H:i:s', strtotime('now'));
echo 'added in table: ' . $counter . PHP_EOL;
echo 'started at: ' . $scriptStart . PHP_EOL;
echo 'ended at: ' . $scriptEnd . PHP_EOL;
Resolved my problem with optimization of my trash code XD
$db = new Database();
$counter = 0;
$scriptStart = date('d.m.Y H:i:s', strtotime('now'));
$lastRemote = $db->lastId('lids');
$lastInner = Lid::all(['id'])->last();
$lastInner = $lastInner->id;
$count = $lastRemote - $lastInner;
if ($count < 0) {
echo 'no new objects, canceled';
return false;
}
$start = $lastInner + 1;
$end = $lastRemote;
$fewEntries = false;
if ($count < 500) {
$fewEntries = true;
$index = $lastInner;
$hundreds = $lastRemote;
} else {
$index = 1;
$hundreds = $count / 100;
$end = $start + 99;
}
if ($fewEntries) {
$leads = $db->itemsBetween('lids', 'id', [$start, $end]);
$uniques = [];
foreach ($leads as $lead) {
if (empty($lead['json_vars'])) continue;
$vars = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $lead['json_vars']);
$json = json_decode($vars, true);
if (!isset($json['ser']['HTTP_COOKIE']) || !str_contains($json['ser']['HTTP_COOKIE'], '_fbc')) continue;
$lead['json_vars'] = $json['ser']['HTTP_COOKIE'];
if (
!isset($uniques[$lead['id']]) ||
$uniques[$lead['id']]['phone'] != $lead['phone'] &&
$uniques[$lead['id']]['ip'] != $lead['ip'] &&
$uniques[$lead['id']]['request_link'] != $lead['request_link']
) {
$uniques[$lead['id']] = $lead;
}
}
foreach ($uniques as $unique) {
$lid = Lid::create($unique);
$counter++;
}
} else {
for ($index; $index < $hundreds; $index++) {
$leads = [];
$leads = $db->itemsBetween('lids', 'id', [$start, $end]);
// var_dump($leads);
// die();
$uniques = [];
foreach ($leads as $lead) {
if (empty($lead['json_vars'])) continue;
$vars = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $lead['json_vars']);
$json = json_decode($vars, true);
if (!isset($json['ser']['HTTP_COOKIE']) || !str_contains($json['ser']['HTTP_COOKIE'], '_fbc')) continue;
$lead['json_vars'] = $json['ser']['HTTP_COOKIE'];
if (
!isset($uniques[$lead['id']]) ||
$uniques[$lead['id']]['phone'] != $lead['phone'] &&
$uniques[$lead['id']]['ip'] != $lead['ip'] &&
$uniques[$lead['id']]['request_link'] != $lead['request_link']
) {
$uniques[$lead['id']] = $lead;
}
}
foreach ($uniques as $unique) {
$lid = Lid::create($unique);
$counter++;
}
$start += 100;
$end += 100;
}
}
$scriptEnd = date('d.m.Y H:i:s', strtotime('now'));
echo 'added in table: ' . $counter . PHP_EOL;
echo 'started at: ' . $scriptStart . PHP_EOL;
echo 'ended at: ' . $scriptEnd . PHP_EOL;

PHP Error 500 Internal Server Error in Codeigniter 3 When large Transaction

I have a problem when execute large transaction in Codeigniter 3.
I create transaction for migrating old data like below:
// Controller
public function migrate_document_get()
{
$this->benchmark->mark('code_start');
$data = $this->Delivery_order_model->read_data_class_from_stock();
foreach ($data as $obj) {
$parameters = $this->Delivery_order_model->read_data_for_do($obj->class_no);
$this->Delivery_order_model->create_data($parameters);
}
$this->benchmark->mark('code_end');
$data['message'] = "Finish migrate document DO";
$data['execution_time'] = round($this->benchmark->elapsed_time('code_start', 'code_end')) . " seconds";
$this->response($data, REST_Controller::HTTP_OK);
}
// Model
function create_data($data)
{
$error = array();
$affected_rows = 0;
$this->mysql->trans_start();
foreach ($data as $row) {
$sql_insert_product = "";
$class_no = $row['class_no'];
$article_vendor = $row['article_vendor'];
$style = $row['style'];
$sku_promo = $row['sku_promo'];
$retail = $row['retail'];
$unique_id = $this->generate_unique_id($class_no, $article_vendor, $style, $sku_promo, $retail);
$sku_no = $class_no . $unique_id . $style . $sku_promo . $retail;
$article_no = $class_no . $style . $sku_promo . $retail;
$res_field = $unique_id . $style . $sku_promo;
$format = array();
$format['dept_no'] = $row['dept_no'];
$format['class_no'] = $class_no;
$format['sku_no'] = $sku_no;
if (!empty($row['ref_no'])) {
$format['ref_no'] = $row['ref_no'];
}
$format['article_vendor'] = $article_vendor;
$format['article_no'] = $article_no;
$format['res_field'] = $res_field;
$format['style'] = $style;
$format['category_no'] = $row['category_no'];
$format['size_no'] = $row['size_no'];
$format['color_no'] = $row['color_no'];
$format['material_no'] = $row['material_no'];
$format['unique_id'] = $unique_id;
$format['sku_promo'] = $sku_promo;
if (!empty($row['exp_promo']) and $row['sku_promo'] != "00") {
$format['exp_promo'] = date('Y-m-d', strtotime(str_replace('/', '-', str_replace("'", "", $row['exp_promo']))));
}
$format['season_code'] = date('ym');
$format['retail'] = $retail;
$format['tag_type'] = $row['tag_type'];
if (!empty($row['image'])) {
$format['image'] = $row['image'];
}
$format['time_create'] = date('Y-m-d H:i:s');
$sql_insert_product = $this->mysql->insert_ignore_string("msr_product", $format);
// Transaction 1 -> INSERT msr_product
$this->mysql->query($sql_insert_product);
$sql_insert_do = "";
$format_doc = "DO" . $class_no . date('Ymd');
$do_id = $this->generate_do_id($format_doc);
$doc_no = $format_doc . $do_id;
$store_no = $row['store_no'];
// INSERT msr_do
$format_insert = array();
$format_insert['do_no'] = $doc_no;
$format_insert['store_no'] = $store_no;
$format_insert['sku_no'] = $sku_no;
$format_insert['do_date1'] = date('Y-m-d', strtotime(date('Ymd')));
$format_insert['do_date2'] = date('Y-m-d', strtotime('60 day', strtotime(date('Ymd'))));
$format_insert['do_status'] = 1;
$format_insert['user_input'] = $row['nik'];
$format_insert['ts_input'] = date('Y-m-d H:i:s');
$format_insert['status_item'] = 0;
$format_insert['qty_store'] = $row['qty'];
$format_update['qty_store'] = "qty_store + " . $row['qty'];
$sql_insert_do = $this->mysql->insert_on_duplicate_update_string("msr_do", $format_insert, $format_update, true, false);
// Transaction 2 -> INSERT msr_do
$this->mysql->query($sql_insert_do);
$affected_rows += $this->mysql->affected_rows();
}
$this->mysql->trans_complete();
if ($this->mysql->trans_status() === FALSE) {
$error = $this->mysql->error();
$error['sql_product'] = $sql_insert_product;
$error['sql_do'] = $sql_insert_do;
}
return $this->commonutil->format_output($affected_rows, $error);
}
When I execute method above in loop,
I facing an issue with error 500 internal server error.
but when I execute method like below one by one, not in the loop it's running normally.
// Controller
public function create_post()
{
$this->benchmark->mark('code_start');
$parameters = $this->post();
if (!empty($parameters)) {
$validate_param = $this->validate_parameter_create($parameters[0]);
if ($validate_param->run() == TRUE) {
$save = $this->Delivery_order_model->create_data($parameters);
if (!empty($save) and $save['total_affected'] > 0) {
$this->benchmark->mark('code_end');
$output['status'] = REST_Controller::HTTP_OK;
$output['error'] = false;
$output['message'] = "Success create delivery order list.";
$output['execution_time'] = $this->benchmark->elapsed_time('code_start', 'code_end') . " seconds.";
$this->response($output, REST_Controller::HTTP_OK);
} else {
$this->benchmark->mark('code_end');
$output['status'] = REST_Controller::HTTP_NOT_MODIFIED;
$output['error'] = true;
$output['error_detail'] = $save['error'];
$output['message'] = "Failed create delivery order list!";
$output['execution_time'] = $this->benchmark->elapsed_time('code_start', 'code_end') . " seconds.";
$this->response($output, REST_Controller::HTTP_NOT_MODIFIED);
}
} else {
$this->benchmark->mark('code_end');
$output['status'] = REST_Controller::HTTP_UNPROCESSABLE_ENTITY;
$output['error'] = true;
$output['error_detail'] = $validate_param->error_array();
$output['message'] = "Required JSON Array! [{.....}]";
$output['execution_time'] = $this->benchmark->elapsed_time('code_start', 'code_end') . " seconds.";
$this->response($output, REST_Controller::HTTP_UNPROCESSABLE_ENTITY);
}
} else {
$this->benchmark->mark('code_end');
$output['status'] = REST_Controller::HTTP_UNPROCESSABLE_ENTITY;
$output['error'] = true;
$output['message'] = "Required parameters!";
$output['execution_time'] = $this->benchmark->elapsed_time('code_start', 'code_end') . " seconds.";
$this->response($output, REST_Controller::HTTP_UNPROCESSABLE_ENTITY);
}
}
// Model
function create_data($data)
{
$error = array();
$affected_rows = 0;
$this->mysql->trans_start();
foreach ($data as $row) {
$sql_insert_product = "";
$class_no = $row['class_no'];
$article_vendor = $row['article_vendor'];
$style = $row['style'];
$sku_promo = $row['sku_promo'];
$retail = $row['retail'];
$unique_id = $this->generate_unique_id($class_no, $article_vendor, $style, $sku_promo, $retail);
$sku_no = $class_no . $unique_id . $style . $sku_promo . $retail;
$article_no = $class_no . $style . $sku_promo . $retail;
$res_field = $unique_id . $style . $sku_promo;
$format = array();
$format['dept_no'] = $row['dept_no'];
$format['class_no'] = $class_no;
$format['sku_no'] = $sku_no;
if (!empty($row['ref_no'])) {
$format['ref_no'] = $row['ref_no'];
}
$format['article_vendor'] = $article_vendor;
$format['article_no'] = $article_no;
$format['res_field'] = $res_field;
$format['style'] = $style;
$format['category_no'] = $row['category_no'];
$format['size_no'] = $row['size_no'];
$format['color_no'] = $row['color_no'];
$format['material_no'] = $row['material_no'];
$format['unique_id'] = $unique_id;
$format['sku_promo'] = $sku_promo;
if (!empty($row['exp_promo']) and $row['sku_promo'] != "00") {
$format['exp_promo'] = date('Y-m-d', strtotime(str_replace('/', '-', str_replace("'", "", $row['exp_promo']))));
}
$format['season_code'] = date('ym');
$format['retail'] = $retail;
$format['tag_type'] = $row['tag_type'];
if (!empty($row['image'])) {
$format['image'] = $row['image'];
}
$format['time_create'] = date('Y-m-d H:i:s');
$sql_insert_product = $this->mysql->insert_ignore_string("msr_product", $format);
// Transaction 1 -> INSERT msr_product
$this->mysql->query($sql_insert_product);
$sql_insert_do = "";
$format_doc = "DO" . $class_no . date('Ymd');
$do_id = $this->generate_do_id($format_doc);
$doc_no = $format_doc . $do_id;
$store_no = $row['store_no'];
// INSERT msr_do
$format_insert = array();
$format_insert['do_no'] = $doc_no;
$format_insert['store_no'] = $store_no;
$format_insert['sku_no'] = $sku_no;
$format_insert['do_date1'] = date('Y-m-d', strtotime(date('Ymd')));
$format_insert['do_date2'] = date('Y-m-d', strtotime('60 day', strtotime(date('Ymd'))));
$format_insert['do_status'] = 1;
$format_insert['user_input'] = $row['nik'];
$format_insert['ts_input'] = date('Y-m-d H:i:s');
$format_insert['status_item'] = 0;
$format_insert['qty_store'] = $row['qty'];
$format_update['qty_store'] = "qty_store + " . $row['qty'];
$sql_insert_do = $this->mysql->insert_on_duplicate_update_string("msr_do", $format_insert, $format_update, true, false);
// Transaction 2 -> INSERT msr_do
$this->mysql->query($sql_insert_do);
$affected_rows += $this->mysql->affected_rows();
}
$this->mysql->trans_complete();
if ($this->mysql->trans_status() === FALSE) {
$error = $this->mysql->error();
$error['sql_product'] = $sql_insert_product;
$error['sql_do'] = $sql_insert_do;
}
return $this->commonutil->format_output($affected_rows, $error);
}
I already resizing on DB temp space
and I already check the method it's running normally
what's wrong with that, please give me some advice.

Using array_map when importing data from xlsx

I am importing some data into a mysql table from an xls file.
On the data, i want to use the mysqli_real_escape_string function, before i insert it into the sql table.
My question is that: where should i put the array_map with the escape function in this code below?
Thanks for help.
if(isset($_POST['submitButton']))
{
if($_FILES['file']['size'] != 0 )
{
if($_FILES["file"]["size"] > 5242880 ) { $error[] = "A fájl mérete maximum 5 MB lehet."; }
$filename = $_FILES['file']['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if(!array_key_exists($ext, $fajl_types)) { $error[] = "Nem engedélyezett fájl típus."; }
if(count($error) == 0 )
{
$path = "../imports/" . date( "Y-m-d" ) . '-' . rand(1, 9999) . '-' . $_FILES['file']['name'];
if(move_uploaded_file($_FILES['file']['tmp_name'], $path ))
{
$file_name = basename($path);
$objPHPExcel = PHPExcel_IOFactory::load('../imports/'.$file_name);
$dataArr = array();
foreach($objPHPExcel->getWorksheetIterator() as $worksheet) {
$worksheetTitle = $worksheet->getTitle();
$highestRow = $worksheet->getHighestRow(); // e.g. 10
$highestColumn = $worksheet->getHighestColumn(); // e.g 'F'
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
for ($row = 1; $row <= $highestRow; ++ $row) {
for ($col = 0; $col < $highestColumnIndex; ++ $col) {
$cell = $worksheet->getCellByColumnAndRow($col, $row);
$val = $cell->getValue();
$dataArr[$row][$col] = $val;
}
}
}
unset($dataArr[1]); // since in our example the first row is the header and not the actual data
$user_pass = "";
$user_reg_date = date("Y-m-d-H:i:s");
$user_last_login = "";
$user_aktivation = "";
$user_vevocsoport = (int)0;
$user_newpass = "";
$user_imported = (int)1;
foreach($dataArr as $val)
{
$sql = "INSERT INTO user
(
user_vnev,
user_knev
)
VALUES
(
'".$val['0']."',
'".$val['1']."'
)";
$import = mysqli_query($kapcs, $sql) or die("IMPORT-ERROR - " . mysqli_error($kapcs));
$ok = 1;
}
}
else
{
$error[] = "A fájl feltöltése nem sikerült.";
}
}
}
else
{
$error[] = "Nem választott ki fájlt.";
}
}
You can add it when building the query. Like this, the escaping and building the query, which are both related to each other, are close to each other in your code.
foreach($dataArr as $val)
{
$escapedVals = array_map(function($value) use ($kapcs) {
return mysqli_real_escape_string($kapcs, $value);
}, array_slice($val, 0, 2));
$sql = 'INSERT INTO user
(
user_vnev,
user_knev
)
VALUES
(
"' . implode ('","', $escapedVals) . '"
)';
$import = mysqli_query($kapcs, $sql) or die("IMPORT-ERROR - " . mysqli_error($kapcs));
$ok = 1;
}

PHP strings concatenation

My code cycles through a CSV file, converting it to XML:
<?php
for ($i = 1; $i < $arraySize; $i++) {
$n = 0;
if (substr($csv[$i][0], 0, 1) == $let) {
$surName = $dom->createElement('name');
$name = $csv[$i][0];
$nameText = $dom->createTextNode($name);
$surName->appendChild($nameText);
$text = str_replace(chr(94), ",", $csv[$i][4]);
$n = $i + 1;
$next = $csv[$n][0];
while ($next == 'NULL') {
$repl = str_replace(chr(94), ",", $csv[$n][4]);
$text = $repl;
$n++;
$next = $csv[$n][0];
}
$bio = $dom->createElement('bio');
$bioText = $dom->createTextNode($text);
$bio->appendChild($bioText);
$person = $dom->createElement('person');
$person->appendChild($surName);
$person->appendChild($bio);
$people->appendChild($person);
}
}
$xmlString = $dom->saveXML();
echo $xmlString;
?>
The problem is the $text = $repl; Typing $text .= $repl; brings:
error on line 1 at column 1: Document is empty.
but omitting the . just gives the last line of text.
the backup code works:
public function test($let){
$csv = $this->readCSV("data\AlphaIndex1M.csv");
$arraySize=sizeof($csv);
$let = strtoupper($let);
//echo '';
for($i=1; $i
echo $csv[$i][0];// .'
echo ', -->'.$csv[$i][4];
$n = $i+1;
$next = $csv[$n][0];
//if($next == 'NULL'){ }
while($next == 'NULL'){
echo $csv[$n][4]. " ";
$n++;
$next=$csv[$n][0];
}
//echo ''
echo '';
}
}
//echo ''
}
You have to initialize your $text before you can append stuff!
So write this before you use it:
$test = "";
(before the while loop or even before the for loop if you want all to be appended)

Print array separating values in groups with same substring

I have an array with a list of domains sorted by domain extensions, like:
values[0] = "programming.ca";
values[1] = "Stackoverflow.ca";
values[2] = "question.com";
values[3] = "answers.com";
values[4] = "AASystems.com";
values[5] = "test.net";
values[6] = "hello.net";
values[7] = "apple.nl";
values[8] = "table.org";
values[9] = "demo.org";
How do I print this array, while automatically grouping it in groups with same domain extension and separated by the line break <br />, so the result will look like this?
programming.ca
Stackoverflow.ca
question.com
answers.com
AASystems.com
test.net
hello.net
apple.nl
table.org
demo.org
Try this.
$ext = "";
for($i = 0; $i < count($values); $i++) {
$parts = explode('.', $values[$i]);
$e = $parts[count($parts) - 1];
if(strcmp($parts[count($parts) - 1], $ext) != 0) {
$ext = $e;
echo '<br/>';
}
echo $values[$i].'<br/>';
}
try this if domain names are in order of domain extensions,
$values[0] = "programming.ca";
$values[1] = "Stackoverflow.ca";
$values[2] = "question.com";
$values[3] = "answers.com";
$values[4] = "AASystems.com";
$values[5] = "test.net";
$values[6] = "hello.net";
$values[7] = "apple.nl";
$values[8] = "table.org";
$values[9] = "demo.org";
$prev_ext = "";
foreach($values as $domain_name)
{
$arr_temp = explode(".", $domain_name);
$domain_ext = $arr_temp[1];
if($prev_ext!=$domain_ext)
{
echo '<br/></br/><br/>';
}
echo $domain_name."<br/>";
$prev_ext = $domain_ext;
}
UPDATE : 2
try this if domain names are not in order of their extensions
$values[0] = "programming.ca";
$values[1] = "AASystems.com";
$values[2] = "demo.org";
$values[3] = "answers.com";
$values[4] = "Stackoverflow.ca";
$values[5] = "test.net";
$values[6] = "hello.net";
$values[7] = "apple.nl";
$values[8] = "table.org";
$values[9] = "question.com";
$arr_domains = array();
foreach($values as $domain_name)
{
$arr_temp = explode(".", $domain_name);
$domain_ext = $arr_temp[1];
$arr_domains[$domain_ext][] = $domain_name;
}
foreach($arr_domains as $ext=>$arr_name)
{
echo "<br/><br/><b>".$ext."</b><br/>";
foreach($arr_name as $name)
{
echo $name."<br/>";
}
}
I edited to hopefully make naming clearer. Basically, explode each domain to get name.extension, then store each name in a dictionary of (extension,domainArray) pairs, then foreach entry in the dictionary, grab the domainArray, then foreach name in the domainArray, echo out the domain name . extension, then a line break, then another line break for every dictionary entry.
<?php
$values[0] = "programming.ca";
$values[1] = "Stackoverflow.ca";
$values[2] = "question.com";
$values[3] = "answers.com";
$values[4] = "AASystems.com";
$values[5] = "test.net";
$values[6] = "hello.net";
$values[7] = "apple.nl";
$values[8] = "table.org";
$values[9] = "demo.org";
$domainsList = [];
foreach ($values as $val) {
$valArr = explode(".", $val);
$name = $valArr[0];
$extension = $valArr[1];
if (isset($domainsList[$extension])) {
$domainsList[$extension][] = $name;
} else {
$domainsList[$extension] = [$name];
}
}
foreach ($domainsList as $extension => $domains) {
foreach ($domains as $domain) {
echo $domain . "." . $extension . "<br />";
}
echo "<br />";
}
Try this code.
$domian = array(
"programming.ca",
"Stackoverflow.ca",
"question.com",
"answers.com",
"AASystems.com",
"test.net",
"hello.net",
"apple.nl",
"table.org",
"demo.org");
$result;
foreach ($domian as $value) {
$arr = explode('.', $value);
$result[$arr[1]][] = $value;
}
print_r($result);

Categories