Using array_map when importing data from xlsx - php

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

Related

How to Skip Header from Excel Spreadsheet While Uploading to MySQL

Is it possible by code to skip the Header (Top Row) in Excel Spreadsheet?
I'm using PHPExcel_Reader to process upload into database.
this image is my data excel
this is my code:
<?php require_once('../../php-excel-reader/excel_reader2.php'); require_once('../../SpreadsheetReader.php'); if (isset($_POST["import"])) { $allowedFileType = ['application/vnd.ms-excel','text/xls','text/xlsx','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet']; if(in_array($_FILES["file"]["type"],$allowedFileType)){ $targetPath = '../assets/uploads/'.$_FILES['file']['name']; move_uploaded_file($_FILES['file']['tmp_name'], $targetPath); $Reader = new SpreadsheetReader($targetPath); $sheetCount = count($Reader->sheets()); for($i=0;$i<$sheetCount;$i++) { $Reader->ChangeSheet($i); foreach ($Reader as $Row) { $student_id = ""; if(isset($Row[0])) { $student_id = mysqli_real_escape_string($conn,$Row[0]); } $roll_no = ""; if(isset($Row[1])) { $roll_no = mysqli_real_escape_string($conn,$Row[1]); } $student_name = ""; if(isset($Row[2])) { $student_name = mysqli_real_escape_string($conn,$Row[2]); } $class_name = ""; if(isset($Row[3])) { $class_name = mysqli_real_escape_string($conn,$Row[3]); } ?>
I use this method for skip header :
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load('FILE.xlsx');
$sheetData = array();
foreach ($spreadsheet->getWorksheetIterator() as $worksheet) {
$worksheetTitle = $worksheet->getTitle();
$highestRow = $worksheet->getHighestRow(); // e.g. 10
$highestColumn = $worksheet->getHighestColumn(); // e.g 'F'
$highestColumnIndex = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($highestColumn);
for ($row = 1; $row <= $highestRow; ++$row) {
for ($col = 0; $col <= $highestColumnIndex; ++$col) {
$cell = $worksheet->getCellByColumnAndRow($col, $row);
$val = $cell->getValue();
$sheetData[$row][$col] = $val;
}
}
}
unset($sheetData[1]); // SKIP HEADER
foreach ($sheetData as $val) {
// set data for upload DB
}
i just unset that from array.

PHP Update MySQL from CSV Skip Row on Error

So basically, I have a CSV file that will be uploaded but not stored on the server and PHP will pull data from it and update a database accordingly.
My Issue is that I am trying to skip the row in the CSV if there is already an entry found in the database but it stops on the first error and does not skip.
Line 62, I added a comment which is where I am trying to get this accomplished.
the ELSE statement after the if (($update == 1) && ($update2 == 1)) has a continue in it, meaning if update and update2 do not == 1 then skip, or so I would have thought but it just stops after the first duplicate serial number is found.
Any help is GREATLY appreciated
public function upload() {
$this->data['token'] = $this->session->data['token'];
$connect = mysqli_connect("localhost", "username", "password", "database");
$this->load->model('setting/mail');
if (isset($_POST["upload"])) {
if ($_FILES['update_cases']['name']) {
$filename = explode(".", $_FILES['update_cases']['name']);
if (end($filename) == "csv") {
$handle = fopen($_FILES['update_cases']['tmp_name'], "r");
fgetcsv($handle);
$this->load->model('sale/order');
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
print "row start<br>";
$order_id = mysqli_real_escape_string($connect, $data[0]);
$product_sn = mysqli_real_escape_string($connect, $data[1]);
$customer_email = mysqli_real_escape_string($connect, $data[2]);
$status = mysqli_real_escape_string($connect, $data[13]);
$rma_number = mysqli_real_escape_string($connect, $data[17]);
$rma_type = mysqli_real_escape_string($connect, $data[18]);
$planned_product = mysqli_real_escape_string($connect, $data[19]);
$tur = mysqli_real_escape_string($connect, $data[20]);
$pi = mysqli_real_escape_string($connect, $data[21]);
$cir = mysqli_real_escape_string($connect, $data[22]);
$cmr = mysqli_real_escape_string($connect, $data[23]);
$waive_return = mysqli_real_escape_string($connect, $data[24]);
$replacement_tracking = mysqli_real_escape_string($connect, $data[26]);
$inventory = mysqli_real_escape_string($connect, $data[27]);
$replacement_sn = mysqli_real_escape_string($connect, $data[28]);
$replacement_sn2 = mysqli_real_escape_string($connect, $data[29]);
$qty_shipped = mysqli_real_escape_string($connect, $data[33]);
$date_shipped = mysqli_real_escape_string($connect, $data[35]);
$result1 = $this->model_sale_order->getOrderById($order_id);
$current_status = $result1['order_status'];
$rma_num = $result1['order_rma'];
$customer_id = $result1['cus_id'];
$regpro_id = $result1['regpro_id'];
$update = 0;
$update2 = 0;
$batch_data = array(
"order_id" => $order_id,
"rpl_tracking" => $replacement_tracking,
"qty_shipped" => $qty_shipped,
"replacement_sn" => $replacement_sn,
"replacement_sn2" => $replacement_sn2,
"inventory" => $inventory,
"rma_type" => $rma_type,
"pi_num" => $pi,
"tur_num" => $tur,
"cir_num" => $cir,
"cmr_num" => $cmr,
"waive_return" => $waive_return,
"update_status" => $status,
"date_shipped" => $date_shipped,
"pre_status" => $current_status,
"comment" => $planned_product,
"planned_product" => $planned_product
);
if ($qty_shipped !== 0) {
$this->load->model('catalog/product');
$this->load->model('catalog/regproduct');
// If Two replacement products
if ($qty_shipped == 2) {
//Check if Serial Number Already Exists (If exists, I want the script to skip this row and move onto the next row in the excel sheet)
$check_sn = $this->model_catalog_regproduct->checkSNBelong2($replacement_sn);
$check_sn2 = $this->model_catalog_regproduct->checkSNBelong2($replacement_sn2);
if ($check_sn) {
$update = 0;
$this->error['error_replacement_sn'] = "SN " . $replacement_sn . " in use!";
} else {
$update = 1;
}
if ($check_sn2) {
$update2 = 0;
$this->error['error_replacement_sn2'] = "SN " . $replacement_sn2 . " in use!";
} else {
$update2 = 1;
}
if (($update == 1) && ($update2 == 1)) {
$replacement_product = $this->model_catalog_product->getProductBySN($replacement_sn);
$replacement_product2 = $this->model_catalog_product->getProductBySN($replacement_sn2);
$defective_product_warranty = $this->model_catalog_regproduct->getRegproductById($customer_id, $regpro_id);
$warr_date = $defective_product_warranty['regpro_warr_date'];
$replacement_model = $replacement_product['m_type'];
$replacement_model2 = $replacement_product2['m_type'];
$replacement_family = $replacement_product['f_type'];
$replacement_family2 = $replacement_product2['f_type'];
$this->model_catalog_regproduct->addRegproductReplacement2($customer_id, $replacement_sn2, $replacement_family2, $replacement_model2, $warr_date);
$this->model_catalog_regproduct->addRegproductReplacement($customer_id, $replacement_sn, $replacement_family, $replacement_model, $warr_date);
$this->model_sale_order->confirmOrder3($this->user->getId(), $batch_data);
if (((int)$current_status) !== ((int)$status)) {
if ((int)$status == 210) {
if ($rma_type != "Standard") {
$template = $this->model_setting_mail->getTemplateByLabel('RMA_PRODUCT_RECEIVED_ADVANCED');
} elseif ($rma_type == "Standard") {
$template = $this->model_setting_mail->getTemplateByLabel('RMA_PRODUCT_RECEIVED_STANDARD');
}
} elseif ((int)$status == 230) {
if ($rma_type != "Standard") {
$template = $this->model_setting_mail->getTemplateByLabel('RMA_REPLACEMENT_PRODUCT_SHIPPED_ADVANCED');
} elseif ($rma_type == "Standard") {
$template = $this->model_setting_mail->getTemplateByLabel('RMA_REPLACEMENT_PRODUCT_SHIPPED_STANDARD');
}
} elseif ((int)$status == 500) {
$template = $this->model_setting_mail->getTemplateByLabel('RMA_CLOSED');
}
if ((int)$template['email_status'] == 1) {
$subject = $template['email_subject'];
$message = $template['email_content'];
// Get Customer Email
$this->load->model('sale/customer');
$order_info = $this->model_sale_customer->getCustomerByEmail($customer_email);
$customer_info = $this->model_sale_customer->getCustomer($order_info['cus_id']);
$email = $customer_info['cus_username'];
$this->load->model('sale/order');
$result_tracking = $this->model_sale_order->getOrderById($order_id);
$replacement_tracking = $result_tracking['order_return_tracking_num'];
$message = str_replace('%FIRSTNAME%', $customer_info['cus_firstname'], $message);
$message = str_replace('%LASTNAME%', $customer_info['cus_lastname'], $message);
$message = str_replace('%RMA%', $rma_num, $message);
$message = str_replace('%TRACKING%', $replacement_tracking, $message);
$mail = new Mail();
$mail->protocol = $this->config->get('mail_protocol');
$mail->hostname = $this->config->get('smtp_host');
$mail->username = $this->config->get('smtp_username');
$mail->password = $this->config->get('smtp_password');
$mail->port = $this->config->get('smtp_port');
$mail->timeout = $this->config->get('smtp_timeout');
$mail->setTo($email);
$mail->setFrom($this->config->get('sender_email'));
$mail->setSender($this->config->get('sender_name'));
$mail->setSubject(html_entity_decode($subject, ENT_QUOTES, 'UTF-8'));
$mail->setText(html_entity_decode($message, ENT_QUOTES, 'UTF-8'));
try {
$mail->send();
}
catch(Exception $e) {
$this->error['warning'] = $e->getMessage();
}
}
}
$this->session->data['success'] = $this->language->get('text_success');
//$this->redirect($this->url->link('report/sale_return', 'token=' . $this->data['token'], 'SSL'));
} else {
print $update."<br>";
print $update2."<br>";
print "Errors<br>";
continue;
}
//row start
//0
//0
//Errors
//row start
//0
//0
//Errors
//row start
//row end
//row start
//row end
//row start
//row end
} else if ($qty_shipped == 1) {
// will do something else
} else if ($qty_shipped == 0) {
// will also do something else
}
} else if (!isset($qty_shipped)) {
// will also do something else
}
print "row end<br>";
}
}
}
}
}
If you want to show all errors, you should use an array, and append the error text to that array. Then use foreach loop on client part to display all errors.
If you use a single variable it will always be what you set it to most recently. For multiple data, you should use an array, or append to string like this: $string .= "appended string"; but for this case I recommend using arrays.

How to access an .xlsb file by php?

I need to access an .xlsb file that does the same function as this code that accesses a .csv file:
<?php
$file1 = __DIR__ . '/download/Trabalhos.csv';
$csv1 = file($file1);
foreach ($csv1 as $row1 => $line1) {
$row1++;
$column1 = str_getcsv($line1, ';');
if ($row1 == 2) {
$column1[6]."<br>";
$valor1 = $column1[6];
}
}
$file2 = __DIR__ . '/download/produtividade do trabalho.csv';
$csv2 = file($file2);
foreach ($csv2 as $row2 => $line2) {
$row2++;
$column2 = str_getcsv($line2, ';');
if ($row2 == 3) {
$column2[9]."<br>";
$valor2 = $column2[9];
}
}
$file3 = __DIR__ . '/download/inatividade do trabalho.csv';
$csv3 = file($file3);
foreach ($csv3 as $row3 => $line3) {
$row3++;
$column3 = str_getcsv($line3, ';');
if ($row3 == 2) {
$column3[0]."<br>";
$valor3 = $column3[0];
}
}
$total = $valor1 * $valor2 * $valor3;
?>
Access the .xlsb file, scroll through the columns and rows, and display the row value on the screen.
Example: "Line 2, Column G(In this case, G = 6)
"A = 0
B = 1
C = 2)"
...
I want it to show me the value of row 2 that is in column G(6).
As in the first if ...
if ($row1 == 2) {
$column1[6]."<br>";
$valor1 = $column1[6];
}
You can use the PHP Excel library from EasyXLS.
$xls = new COM("EasyXLS.ExcelDocument");
$rows = $xls->easy_ReadXLSBActiveSheet_AsList("Trabalhos.xlsb");
for ($row1=0; $row1<$rows->size(); $row1++)
{
$rowLine = $rows->elementAt($row1);
if ($row1 == 2) {
$column1[6]."<br>";
$valor1 = $row->elementAt(6);
}
}
You can find some more code samples about importing data from xlsb file.
For your purpose you can use PHPOffice/PHPExcel

PHPexcel to array. Help formatting array and to rid array of NULL values

My spreadsheet will always have column B,C,D,E,F,G row 3 = address, name, phone, department, etc.. The data from the cells beneath (some empty some populated) 1234 x street, 1234 y street, 555-5555, HR, etc. So if My array could look like this:
[1] =>array(
['address1'] =>'1234 x street'
['name1'] =>'1234 y street'
['phone1'] =>'555-5555'
...etc
['department1'] =>'HR'
[2] =>array(
['address2'] =>'1234 x street'
['name2'] =>'1234 y street'
['phone2'] =>'555-5555'
...etc
['department2'] =>'HR'
My current code is:
<SNIP>
$objReader->setReadDataOnly(true);
$objPHPExcel = $objReader->load($inputFileName);
$objWorksheet = $objPHPExcel->getActiveSheet();
if($header){
$highestRow = $objWorksheet->getHighestRow();
$highestColumn = $objWorksheet->getHighestColumn();
$headingsArray = $objWorksheet->rangeToArray('A1:'.$highestColumn.'1',null, true, true, true);
$headingsArray = $headingsArray[1];
$r = -1;
$namedDataArray = array();
for ($row = 2; $row <= $highestRow; ++$row) {
$dataRow = $objWorksheet->rangeToArray('A'.$row.':'.$highestColumn.$row,null, true, true, true);
if ((isset($dataRow[$row]['A'])) && ($dataRow[$row]['A'] > '')) {
++$r;
foreach($headingsArray as $columnKey => $columnHeading) {
$namedDataArray[$r][$columnHeading] = $dataRow[$row][$columnKey];
}
}
}
}
else{
$namedDataArray = $objWorksheet->toArray(null,true,true,true);
}
Research suggests I can use one of the following methods however I need help putting it all together:
$column = 'IV';
$columnIndex = PHPExcel_Cell::columnIndexFromString($column);
$adjustment = -2;
$currentColumn = 'BZ';
$columnIndex = PHPExcel_Cell::columnIndexFromString($currentColumn);
$adjustedColumnIndex = $columnIndex + $adjustment;
$adjustedColumn = PHPExcel_Cell::stringFromColumnIndex($adjustedColumnIndex - 1);
I ended up not using any of the native classes for the sorting piece, lowered overhead by just writing it myself as follows:
<?php
//require 'FirePHPCore/fb.php'; This section was just to use FirePHP so I could see the JSON output without using html.
//ob_start('ob_gzhandler');
//FB::info('Hello, FirePHP');
//FB::log('Log message');
//FB::info('Info message');
//FB::warn('Warn message');
//FB::error('Error message');
require_once dirname(__FILE__) . '/classes/PHPExcel.php';
// Include PHPExcel_IOFactory
include 'classes/PHPExcel/IOFactory.php';
$inputFileName = './uploads/fw.xls';
$inputFileType = PHPExcel_IOFactory::identify($inputFileName);/** Identify the type of $inputFileName **/
$objReader = PHPExcel_IOFactory::createReader($inputFileType);/** Create a new Reader of the type that has been identified **/
$objReader->setReadDataOnly(true); /** Set read type to read cell data only **/
$objPHPExcel = $objReader->load($inputFileName);/** Load $inputFileName to a PHPExcel Object **/
$objWorksheet = $objPHPExcel->getActiveSheet();//Get worksheet and built array with first row as header
// stuff all tabs into their own array
$sheetNames = $objPHPExcel->getSheetNames();
foreach ($sheetNames as $sheet) {
$sheet2 = preg_replace("/\s+/","_",$sheet);
//print "$sheet: $sheet2<br>\n";
${$sheet2} = $objPHPExcel->getSheetByName($sheet);
}
// print_r($Network_Security);
//exit;
// parse each tab, tack onto end of $prejson array
$prejson = [];
// parse network security
//use class to find data range
$highestRow = $Network_Security->getHighestRow();
$range = $Network_Security->calculateWorksheetDimension();
// manually narrow range columns
$range = preg_replace("/A/","B",$range);
$range = preg_replace("/L/","K",$range);
//create array of data rows
$rows = $Network_Security->rangeToArray($range);
$active = 0;
//loop through each row
foreach ($rows as $row) {
if (preg_match("/Do not edit the data/",$row[0])) { $active = 2; continue; }
if (preg_match("/^Line/",$row[0]) && $active == 0) { $active = 1; } //show header
if ($row[0] == "") { $active = 0; continue; }
if ($active == "1") {
//key array
array_unshift($row,"netsec");
// stuff to prejson
array_push($prejson,$row);
}
}
// end netsec
// parse network translation
$highestRow = $Network_Translation->getHighestRow();
$range = $Network_Translation->calculateWorksheetDimension();
$range = preg_replace("/A/","B",$range);
$range = preg_replace("/J/","G",$range);
$rows = $Network_Translation->rangeToArray($range);
$active = 0;
foreach ($rows as $row) {
if (preg_match("/^Source/",$row[0]) && $active == 0) { $active = 1; } //show header
if (preg_match("/Do not edit the data/",$row[0])) { $active = 2; continue; }
if ($row[0] == "") { $active = 0; continue; }
if ($active == "1") {
//key array
array_unshift($row,"nettrans");
// stuff to prejson
array_push($prejson,$row);
}
}
// end nettrans
// parse routing
$highestRow = $Routing->getHighestRow();
$range = $Routing->calculateWorksheetDimension();
$range = preg_replace("/A/","B",$range);
$range = preg_replace("/H/","G",$range);
$rows = $Routing->rangeToArray($range);
$active = 0;
foreach ($rows as $row) {
if (preg_match("/Do not edit the data/",$row[0])) { $active = 2; continue; }
//if (preg_match("/^Add/",$row[0]) && $active == 0) { $active = 1; continue; } //hide header
if (preg_match("/^Add/",$row[0]) && $active == 0) { $active = 1; } //show header
if ($row[0] == "") { $active = 0; continue; }
if ($active == "1") {
// key array
array_unshift($row,"rtg");
// stuff to prejson
array_push($prejson,$row);
}
}
// end routing
//print "<pre>";
//var_dump($prejson);
$json = json_encode($prejson);
//$json_string = prettyPrint($json);
$json_string = json_encode($json,JSON_PRETTY_PRINT); //remove ,JSON_PRETTY_PRINT
print $json;
//print "</pre>";
function prettyPrint( $json )
{
$result = '';
$level = 0;
$in_quotes = false;
$in_escape = false;
$ends_line_level = NULL;
$json_length = strlen( $json );
for( $i = 0; $i < $json_length; $i++ ) {
$char = $json[$i];
$new_line_level = NULL;
$post = "";
if( $ends_line_level !== NULL ) {
$new_line_level = $ends_line_level;
$ends_line_level = NULL;
}
if ( $in_escape ) {
$in_escape = false;
} else if( $char === '"' ) {
$in_quotes = !$in_quotes;
} else if( ! $in_quotes ) {
switch( $char ) {
case '}': case ']':
$level--;
$ends_line_level = NULL;
$new_line_level = $level;
break;
case '{': case '[':
$level++;
case ',':
$ends_line_level = $level;
break;
case ':':
$post = " ";
break;
case " ": case "\t": case "\n": case "\r":
$char = "";
$ends_line_level = $new_line_level;
$new_line_level = NULL;
break;
}
} else if ( $char === '\\' ) {
$in_escape = true;
}
if( $new_line_level !== NULL ) {
$result .= "\n".str_repeat( "\t", $new_line_level );
}
$result .= $char.$post;
}
return $result;
}
?>
Now I just need to get the hook so that when dropzone.js completes it will autopopulate the .js form.

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