Get 2 contents per line - php

I was wondering I can get these to the ID and the Name from this code:
stuffyd[1] = {name: "Item 1"};
stuffyd[2] = {name: "Item 2"};
stuffyd[3] = {name: "Item 3"};
stuffyd[4] = {name: "Item 4"};
stuffyd[5] = {name: "Item 5"};
stuffyd[6] = {name: "Item 6"};
The ID is in the [IDHERE] and the name, obviously is after name:
I tried using explode and loops but that didn't work out well. Here was my code:
<?php
function getItemName($i) {
$itemNameFile = file_get_contents('test.txt');
$itemName = explode('"', $itemNameFile);
return $itemName[$i];
}
function getItemID($i) {
$itemIDFile = file_get_contents('test.txt');
$itemID1 = explode('stuffyd[', $itemIDFile);
$itemID = explode(']', $itemID1[$i]);
return $itemID[0];
}
function getNamesID() {
for($i = 1; $i < 6; $i++) {
//if ($i & 1) {
$itemName1 = getItemName($i);
//}
//if($i < 6) {
$itemID1 = getItemID($i);
//}
}
echo $itemName1 . ":" . $itemID1 . chr(10);
}
getNamesID();
?>
This is the output:
Item 3:5
What can I do?

// read the file once only
$data = file_get_contents('test.txt');
// use preg_match_all to parse the data
preg_match_all("/stuffyd\[([0-9]+)\].*\"(.*?)\"/im", $data, $matches);
// you could echo here but let's convert the matches into a usable array
$count=count($matches);
for ($i=0; $i<$count; $i++){
$items[$matches[1][$i]]=$matches[2][$i];
}
// and then echo out the key and value of each pair
foreach ($items as $id => $name){
echo $name . ':' . $id . chr(10);
}
http://uk1.php.net/preg_match_all

The answers by #Popnoodles and #Barmar are best using preg_match_all.
But to understand why your code didn't work, there are 3 issues.
(1) in function getItemName($i) when you explode $itemNameFile the array in $itemName look like -
Array
(
[0] => stuffyd[1] = {name:
[1] => Item 1
[2] => };
stuffyd[2] = {name:
[3] => Item 2
[4] => };
stuffyd[3] = {name:
[5] => Item 3
[6] => };
stuffyd[4] = {name:
[7] => Item 4
[8] => };
stuffyd[5] = {name:
[9] => Item 5
[10] => };
stuffyd[6] = {name:
[11] => Item 6
[12] => };
)
So you need to do
return $itemName[$i+($i-1)];
(2) in function getNamesID() you are only looping through 5 time
for($i = 1; $i < 6; $i++)
to get all 6 you need to use <=6
for($i = 1; $i <= 6; $i++)
(3) in function getNamesID() your echo ... is outside of your for() loop, so you will only get the last instance. Move the for() loop closing bracket to after your echo -
echo $itemName1 . ":" . $itemID1 . chr(10);
} // end for()
} // end function
So now your code would look like -
<?php
function getItemName($i) {
$itemNameFile = file_get_contents('test.txt');
$itemName = explode('"', $itemNameFile);
return $itemName[$i+($i-1)];
}
function getItemID($i) {
$itemIDFile = file_get_contents('test.txt');
$itemID1 = explode('stuffyd[', $itemIDFile);
$itemID = explode(']', $itemID1[$i]);
return $itemID[0];
}
function getNamesID() {
for($i = 1; $i <= 6; $i++) {
$itemName1 = getItemName($i);
$itemID1 = getItemID($i);
echo $itemName1 . ":" . $itemID1 . chr(10);
}
}
getNamesID();
?>

$contents = file_get_contents("test.txt");
preg_match_all('/stuffyd\[(\d+)\].*=name:\s*"(.*)"/', $contents, $matches, PREG_SET_ORDER);
foreach ($matches as $match) {
echo $match[2] . ':' . $match[1] . "\n";
}

Related

How to split array to multiple csv files using PHP

Help!
I want to make this part of code shorter and more transformative. My $named array looks like:
Array
(
[0] => Array
(
[0] => Array
(
[0] => Header
)
[1] => Array
(
[0] => some text
[1] => some text
)
)
[1] => Array
(
[0] => Array
(
[0] => Header
)
[1] => Array
(
[0] =>
[1] => some text
)
[2] => Array
(
[0] => some text
)
)
)
So, I would like to save to a new csv file if the number of "header" exceeds 100. How can I open and close a file with the correct index without having to manually type "/named_1" or "/named_2"? At the moment I have a y variable that goes through the $named array and writes to the file until there are 100 headers. How can I not repeat the code?
Also each line must have a total of 38 semicolons.
$file = fopen(__DIR__ . '/named_1.csv', 'w');
$file_2 = fopen(__DIR__ . '/named_2.csv', 'w');
$file_3 = fopen(__DIR__ . '/named_3.csv', 'w');
$y=0;
foreach ($named as $array) {
foreach($array as $row){
if($y < 100){
$line = '';
for ($i=0; $i <= 38; $i++) {
if (count($row) > $i) {
$line .= $row[$i];
($i != 38 ? $line .= ';' : '');
} else {
($i != 38 ? $line .= ';' : '');
}
}
fwrite($file, $line.PHP_EOL);
}
if($y > 99 && $y <200){
$line = '';
for ($i=0; $i <= 38; $i++) {
if (count($row) > $i) {
$line .= $row[$i];
($i != 38 ? $line .= ';' : '');
} else {
($i != 38 ? $line .= ';' : '');
}
}
fwrite($file_2, $line.PHP_EOL);
}
if($y > 199 && $y <300){
$line = '';
for ($i=0; $i <= 38; $i++) {
if (count($row) > $i) {
$line .= $row[$i];
($i != 38 ? $line .= ';' : '');
} else {
($i != 38 ? $line .= ';' : '');
}
}
fwrite($file_3, $line.PHP_EOL);
}
}
$y++;
}
fclose($file);
touch( __DIR__ . '/named_1.csv');
fclose($file_2);
touch( __DIR__ . '/named_2.csv');
fclose($file_3);
touch( __DIR__ . '/named_3.csv');
Please try the following code. I added a function for composing filename for different needs.
function composeFilename($k, $mod, $type=1)
{
switch($type)
{
// for named_1-100.csv, named_101-200.csv, ...
case 1:
$from = $k - $mod + 2;
$to = $k+1;
$suffix = $from . "_" .$to;
break;
// for named_0-99.csv, named_100-199.csv, ...
case 2:
$from = $k - $mod + 1;
$to = $k;
$suffix = $from . "_" .$to;
break;
// for named_1.csv, named_2.csv, ...
default:
$suffix = ($k % $mod)+1;
}
return "named_$suffix.csv";
}
$lines = [];
$mod = 100;// The max number of rows in each output file
$outputDirectory = __DIR__ . "/";
$lastIndex = count($named) - 1;
foreach ($named as $k => $array){
foreach($array as $row){
$lines[] = trim(implode(";", $row));
}
// Write output file for every $mod lines or for the rest
if(($k+1) % $mod == 0 || $k == $lastIndex){
$filename = $outputDirectory . composeFilename($k, $mod);
if(file_put_contents($filename, implode(PHP_EOL, $lines))){
// Reset lines array for the next chunk
$lines = [];
}
else {
die("$filename could not be saved.");
}
}
}

How can i print array as row and column in phpExcel?

Here is my array output in browser which i need to print as row and column associatively in PHPEXCEL.Please suggest me how to export it as row and columns.
FirstArray
(
[0] => EY>Yes
[1] => Media Type>Category B
[2] => Coverage Type>Quote
[3] => Industry Programs>Communications
[4] => Score>1
)
code -
while ($i < count($labels)) {
$j = 0;
while ($j < count($dd1)) {
// for($j=0;$j<count($dd1);$j++) {
$temp = explode(">", $dd1[$j]);
if ($temp[0] == $labels[$i]) {
$name = explode(">", $dd1[$j]);
echo '<pre>First';
print_r($name);
}
$j++;
}
complete code i am trying to print $name array as row and column -
$inn_table = "";
for($i=0;$i<count($labels);$i++) {
for($j=0;$j<count($dd1);$j++) {
$temp = explode(">",$dd1[$j]);
if($temp[0]==$labels[$i]) {
$name = explode(">",$dd1[$j]);
//here i need to print my $name array data
}
}
echo $inn_table;
At first step you can collect once all column names and create first static row, which will work as columns:
foreach($labels[0] as $ind=>$label){
$letter = range('A', 'Z')[$ind];
$tmp = explode('>',$label);
$col_names[] = $tmp[0];
echo $letter.'1'."\r\n";
//$objPHPExcel->getActiveSheet()->setCellValue($letter.'1',$tmp[0]);
echo "Column -> $tmp[0] \r\n";
}
Now you can work with other data:
foreach ($labels as $ind=>$item){
$index = $ind + 2;
foreach($item as $ind2=>$data){
$letter = range('A', 'Z')[$ind2];
echo "$letter$index \r\n";
$val = explode('>',$data);
//$objPHPExcel->getActiveSheet()->setCellValue("$letter$index",$val[1]);
echo "Value at $index -> $val[1] \r\n\r\n";
}
echo "\r\n\r\n";
}
Demo
Note: this code is OK for A..Z range column indexes, for others you need to update this code.

add the key name and value for the same array in php

I have some array like this how can i split the key and value in php ?
[A0E4NL014XVM273] => Array
(
[0] => qexixdb
)
[A0E4UK024XVM014_Clone] => Array
(
[0] => pe8w3100
[1] => pe8w3100
)
Tried Query
foreach($vm_array as $vmkey=> $vmvalue){
$varray[] = $vmvalue;
/*foreach($vmvalue as $vmvalue=> $vmvalufmarray){
$vm_array[$vmkey][] = $vmvalufmarray.',';
}*/
}
Expected Output
[A0E4UK024XVM014_Clone] => pe8w3100,pe8w3100
You need to make a function called implode().
foreach($vm_array as $vmkey=> $vmvalue){
$varray[$vmkey] = implode(",", $vmvalue);
}
print_r($varray);
Try using PHP's implode on the inner array;
foreach($vm_array as $vmkey => $vmvalue){
$vm_array[$vmkey] = implode(",", $vmvalue);
}
I tried your example and simulated my own, if my understanding is right, if you want to retain them in the array.
$test = array("[A0E4NL014XVM273]" => array("qexixdb"),"[A0E4UK024XVM014_Clone]" => array("pe8w3100","pe8w3100"));
echo "<pre>";
var_dump($test);
echo "</pre>";
$new_arr_ = array();
foreach($test as $id => $value) {
$new_val = "";
for($i = 0, $ctr_val = count($value); $i < $ctr_val; $i++) {
$old_id = "";
if($id != $old_id) {
if($i < ($ctr_val - 1)) {
$new_val .= $value[$i] . ",";
} else {
$new_val .= $value[$i];
}
$old_id = $id;
}
}
$new_arr_[] = array($id => $new_val);
}
echo "<pre>";
var_dump($new_arr_);
echo "</pre>";
Or if just one array:
$new_arr_ = array();
foreach($test as $key=> $value){
$new_arr_[key] = implode(",", $value);
}
echo "<pre>";
var_dump($new_arr_);
echo "</pre>";
Hope it helps.

Walk array recursively and print the path of the walk

Can someone help me with some code or instructions on how to walk recursively an array and when reaching the last element print the full path to it? A simple echo will work because I will adapt the code to some other function I'm developing.
The function doesn't need to figure the array dimension because this param will be passed:
Example:
$depth = 8;
$array[1][3][5][6][9][5][8][9];
When function reachs the 8th element it print all the path to it:
//print path
'1 -> 3 -> 5 -> 6 -> 9 -> 5 -> 8 -> 9'
As I said, only printing in this format will work cause I will implement the code into some other function.
array keys can have the same value. Obviously not the same value in the same sequence for the entire arary.
Updated:
Walk recursively function:
$someArray[1][2][3] = 'end';
$someArray[1][2][6] = 'end';
$someArray[1][3][6] = 'end';
$someArray[4][3][7] = 'end';
function listArrayRecursive(&$array_name, $ident = 0){
if (is_array($array_name)){
foreach ($array_name as $k => &$v){
if (is_array($v)){
for ($i=0; $i < $ident * 10; $i++){ echo " "; }
echo $k . " : " . "<br>";
listArrayRecursive($v, $ident + 1);
}else{
for ($i=0; $i < $ident * 10; $i++){ echo " "; }
echo $k . " : " . $v . "<br>";
}
}
}else{
echo "Variable = " . $array_name;
}
}
listArrayRecursive($someArray);
Will print:
1 :
2 :
3 : end
6 : end
3 :
6 : end
4 :
3 :
7 : end
Now, how can I also print the path of the array everytime it reaches the end? For example:
1 :
2 :
3 : end : path -> 1,2,3
6 : end : path -> 1,2,6
3 :
6 : end : path -> 1,3,6
4 :
3 :
7 : end : path -> 4,3,7
EDITED CODE ADDING A THIRD PARAM TO RECORD THE PATH:
$someArray[1][2][3] = 'end';
$someArray[1][2][6] = 'end';
$someArray[1][3][6] = 'end';
$someArray[4][3][7] = 'end';
$someArray[3][2] = 'end';
function listArrayRecursive(&$array_name, $ident = 0, $path = null){
foreach ($array_name as $k => &$v){
if (is_array($v)){
for ($i=0; $i < $ident * 10; $i++){ echo " "; }
echo $k . " : " . "<br>";
$path .= $k . ', ';
listArrayRecursive($v, $ident + 1, $path);
}else{
for ($i=0; $i < $ident * 10; $i++){ echo " "; }
echo $k . " : " . $v . ' - path -> ' . $path . "<br>";
}
}
}
listArrayRecursive($someArray);
Will print:
1 :
2 :
3 : end - path -> 1, 2,
6 : end - path -> 1, 2,
3 :
6 : end - path -> 1, 2, 3,
4 :
3 :
7 : end - path -> 1, 4, 3,
3 :
2 : end - path -> 1, 4, 3,
You could employ a RecursiveIteratorIterator (docs) to take the hard work out of recursing through the arrays.
function listArrayRecursive($someArray) {
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($someArray), RecursiveIteratorIterator::SELF_FIRST);
foreach ($iterator as $k => $v) {
$indent = str_repeat(' ', 10 * $iterator->getDepth());
// Not at end: show key only
if ($iterator->hasChildren()) {
echo "$indent$k :<br>";
// At end: show key, value and path
} else {
for ($p = array(), $i = 0, $z = $iterator->getDepth(); $i <= $z; $i++) {
$p[] = $iterator->getSubIterator($i)->key();
}
$path = implode(',', $p);
echo "$indent$k : $v : path -> $path<br>";
}
}
}
This example is to give you idea, not to solve the actual task.
function recursiveSearch($array,$search){
foreach($array as $key=>$val){
if($val==$search)return $key;
$x=recursiveSearch($array[$key],$search);
if($x)return $key.' -> '.$x;
}
}
echo recursiveSearch($array,'search');
If no match is found, null is returned.
$a= array(1,2,3,4,5,6);
$val = end($a);
print_array($a,$val);
function print_array(&$arr, $val)
{
if ($val === false)
return;
$curr = prev($arr);
print_array($arr,$curr);
echo $val;
}
I just wrote a function that makes recursive looping a bit easier:
Similar to array_walk_recursive but with some extra functionality
public static function walk($array, $callback, $custom = null, $recursive = false, $info = [])
{
$r = $recursive;
if (gettype($r) === 'integer') {
$r--;
}
$info['depth'] = empty($info)?1:$info['depth'] + 1;
$info['count'] = count($array);
$info['i'] = 1;
foreach($array as $k => $v) {
if (is_array($v) && $r > 0) {
$array[$k] = static::walk($v, $callback, $custom, $r, $info);
} else {
$array[$k] = $callback($v, $k, $custom, $info);
}
$info['i'] ++;
}
return $array;
}
public static function walkable($v, $k, $custom, $info)
{
if (is_string($v)) {
return $v." [ custom: {$custom['key']} ] [ level: ".$info['depth'].' | No '.$info['i'].' of '.$info['count']." ]";
}
return $v;
}
Called like so:
$result = Namespace\ClassName::walk($array, ['Namespace\ClassName', 'walkable'], ['key'=>'value'], true);
Setting recursive to false will only evaluate the first level.
Setting recursive to true will cause it to traverse the entire array.
Setting recursive to an integer will cause it to only traverse to that depth.
Walkable functions can be referenced or passed to callback as anonymous function.
(expects: value, key, custom, info)
The returned value replace the current value.
Custom data can be passed and some additional info is provided for you.
You can expand on the walk function if you need additional info.
I had similar problem. Here is a Depth-First Search-ish solution(no path depth included, it reaches until the very end of the array). Comment the 'if' statement if u don't want to include the value:
$output = array();
retrievePath($someArray, $output);
function retrievePath($someArray, array &$pathKeeper)
{
if(!is_array($someArray)){ // $someArray == "end"
$element = array_pop($pathKeeper) ?? '';// if the array is empty pop returns null, we don't want that
array_push($pathKeeper, $element . '->'. $someArray);
} else{
end($someArray);//we want to get the last element from the array so we move the internal pointer to it's end
$endElKey = key($someArray);//take the key where the pointer is
reset($someArray);
foreach($someArray as $key=>$value){
$element = array_pop($pathKeeper);
array_push($pathKeeper, $element === null ? $key : $element . '->' . $key);// we don't want '->' at the beginning
retrievePath($value, $pathKeeper);
if($key != $endElKey) //we check whether this is not the last loop
array_push($pathKeeper, $element);
}
}
}
<?php
function printListRecursive($a, $var='', $i = 0) {
if (!is_array($a)) {
$var .= $a;
return $var;
}
$string = "";
foreach ($a as $k => $value) {
$string .= str_repeat(" ", $i) .' - '. $k . ':';
if (!is_array($value)) {
$string .= $value . '<br />';
} else {
$string .= '<br />';
$string .= printListRecursive($value, $var, $i + 1);
}
}
return $string;
}
$test_array = [
'America' => [
'Argentina' => 'Buenos Aires',
'Peru' => 'Lima'
],
'Europe' => [
'Ireland' => 'Dublin',
'France' => 'Paris',
'Italy' => 'Rome'
]
];
$result = printListRecursive($test_array);
echo $result;
?>
Check code here
I came up with the following function based on #salathe's one. It returns an array where each element is an array containing the leaf at index 0 and the array of the path keys at index 1:
function loosenMultiDimensionalArrayPathForEachVal($array) {
$iterator = new \RecursiveIteratorIterator(new \RecursiveArrayIterator($array), \RecursiveIteratorIterator::SELF_FIRST);
$iterator->rewind();
$res = [];
foreach ($iterator as $v) {
$depth = $iterator->getDepth();
for ($path = array(), $i = 0, $z = $depth; $i <= $z; $i++) {
$path[] = $iterator->getSubIterator($i)->key();
}
$leaf = $array;
foreach ($path as $pathKey) {
$leaf = $leaf[$pathKey];
}
if (!is_array($leaf)) {
$res[] = [
$v,
$path
];
}
}
return $res;
}
The main reason I implemented this one is that $iterator->hasChildren() returns true if the current iterated leaf is an object. Therefore, I wouldn't be able to get the path of it that way.
I found this solution, which also keeps into account if elements of the structure are arrays:
$file_contents=file_get_contents("data.json");
$json_dump=json_decode($file_contents);
printPath($json_dump, '', "" ,"");
function printPath($the_array, $path, $prevType) {
// Parse all elements of a structure
// and print full PHP path to each one.
foreach($the_array as $key => $value) {
if(is_array($value)) {
// Array element cannot be directly printed: process its items as objects:
printPath($value, $path . $key , "array");
} else {
if (!is_object($value)) { // If the element is not an object, it can be printed (it's a leaf)
if(is_string($value)) {
$finalValue = '"' . $value . '"';
} else {
$finalValue = $value;
}
if($prevType == "array") {
// If array element, add index in square brackets
echo($path . "[" . $key . "] = " . $finalValue . "<br>");
} else {
echo($path . $key . " = " . $finalValue . "<br>");
}
} else { // else store partial path and iterate:
if($prevType == "array") {
// Path of array element must contain element index:
printPath($value, $path . "[" . $key . "]->" , "dummy");
} else {
printPath($value, $path . $key . "->", "dummy");
}
}
}
}
}
Example output:
status->connections->DSS-25->band = "X"
status->connections->DSS-25->endAt = "2019-11-20T20:40:00.000Z"
status->connections->DSS-25->startAt = "2019-11-20T12:40:00.000Z"
geometry[0]->obs[0]->name = "UDSC64"
geometry[0]->obs[0]->hayabusa2->azm = 90.34
geometry[0]->obs[0]->hayabusa2->alt = -20.51
In case anybody is interested, here it is the port to Javascript:
function iterate(obj, stack, prevType) {
for (var property in obj) {
if ( Array.isArray(obj[property]) ) {
//console.log(property , "(L=" + obj[property].length + ") is an array with parent ", prevType, stack);
iterate(obj[property], stack + property , "array");
} else {
if ((typeof obj[property] != "string") && (typeof obj[property] != "number")) {
if(prevType == "array") {
//console.log(stack + "[" + property + "] is an object, item of " , prevType, stack);
iterate(obj[property], stack + "[" +property + "]." , "object");
} else {
//console.log(stack + property , "is " , typeof obj[property] , " with parent ", prevType, stack );
iterate(obj[property], stack + property + ".", "object");
}
} else {
if(prevType == "array") {
console.log(stack + "[" + property + "] = "+ obj[property]);
} else {
console.log(stack + property , " = " , obj[property] );
}
}
}
}
}
iterate(object, '', "File")
You can add a third parameter which holds the actual path as String. At the end you can output it then.

How to trim white spaces of array values in php

I have an array as follows
$fruit = array(' apple ','banana ', ' , ', ' cranberry ');
I want an array which contains the values without the white spaces on either sides but it can contain empty values how to do this in php.the output array should be like this
$fruit = array('apple','banana', ',', 'cranberry');
array_map and trim can do the job
$trimmed_array = array_map('trim', $fruit);
print_r($trimmed_array);
Multidimensional-proof solution:
array_walk_recursive($array, function(&$arrValue, $arrKey){ $arrValue = trim($arrValue);});
array_walk() can be used with trim() to trim array
<?php
function trim_value(&$value)
{
$value = trim($value);
}
$fruit = array('apple','banana ', ' cranberry ');
var_dump($fruit);
array_walk($fruit, 'trim_value');
var_dump($fruit);
?>
See 2nd example at http://www.php.net/manual/en/function.trim.php
I had trouble with the existing answers when using multidimensional arrays. This solution works for me.
if (is_array($array)) {
foreach ($array as $key => $val) {
$array[$key] = trim($val);
}
}
If the array is multidimensional, this will work great:
//trims empty spaces in array elements (recursively trim multidimesional arrays)
function trimData($data){
if($data == null)
return null;
if(is_array($data)){
return array_map('trimData', $data);
}else return trim($data);
}
one sample test is like this:
$arr=[" aaa ", " b ", "m ", [" .e ", " 12 3", "9 0 0 0 "]];
print_r(trimData($arr));
//RESULT
//Array ( [0] => aaa [1] => b [2] => m [3] => Array ( [0] => .e [1] => 12 3 [2] => 9 0 0 0 ) )
$fruit= array_map('trim', $fruit);
array_map('trim', $data) would convert all subarrays into null. If it is needed to trim spaces only for strings and leave other types as it is, you can use:
$data = array_map(
function ($item) {
return is_string($item) ? trim($item) : $item;
},
$data
);
If you want to trim and print one dimensional Array or the deepest dimension of multi-dimensional Array you should use:
foreach($array as $key => $value)
{
$array[$key] = trim($value);
print("-");
print($array[$key]);
print("-");
print("<br>");
}
If you want to trim but do not want to print one dimensional Array or the deepest dimension of multi-dimensional Array you should use:
$array = array_map('trim', $array);
If you don't want to lose elements of an associative array, DONT use array_walk or array_map!
A slightly shorter version of the foreach solution:
foreach($array as &$val)
$val = trim($val);
This works for associative arrays.
function generateRandomString($length = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
function generateRandomSpaces() {
$output = '';
$i = rand(1, 10);
for ($j = 0; $j <= $i; $j++) {
$output .= " ";
}
return $output;
}
// Generating an array to test
$array = [];
for ($i = 0; $i <= 1000; $i++) {
$array[] = generateRandomSpaces() . generateRandomString(10) . generateRandomSpaces();
}
// ARRAY MAP
$start = microtime(true);
for ($i = 0; $i < 100000; $i++) {
$trimmed_array=array_map('trim',$array);
}
$time = (microtime(true) - $start);
echo "Array map: " . $time . " seconds\n";
// ARRAY WALK
$start = microtime(true);
for ($i = 0; $i < 100000; $i++) {
array_walk($array, 'trim');
}
$time = (microtime(true) - $start);
echo "Array walk : " . $time . " seconds\n";
// FOREACH
$start = microtime(true);
for ($i = 0; $i < 100000; $i++) {
foreach ($array as $index => $elem) {
$array[$index] = trim($elem);
}
}
$time = (microtime(true) - $start);
echo "Foreach: " . $time . " seconds\n";
// FOR
$start = microtime(true);
for ($i = 0; $i < 100000; $i++) {
for ($j = 0; $j < count($array) - 1; $j++) {
$array[$j] = trim($array[$j]);
}
}
$time = (microtime(true) - $start);
echo "For: " . $time . " seconds\n";
The output of the code above is:
Array map: 8.6775720119476 seconds
Array walk: 10.423238992691 seconds
Foreach: 7.3502039909363 seconds
For: 9.8266389369965 seconds
This values of course may change but I would say foreach is the best option.
Trim in array_map change type if you have NULL in value.
Better way to do it:
$result = array_map(function($v){
return is_string($v)?trim($v):$v;
}, $array);
simply you can use regex to trim all spaces or minify your array items
$array = array_map(function ($item) {
return preg_replace('/\s+/', '', $item);
}, $array);
function trim_value(&$value)
{
$value = trim($value);
}
// ut_sreco_dis Module
public function disExcelUpload($file=""){
ini_set('MAX_EXECUTION_TIME', -1);
ini_set('memory_limit', '-1');
$file_upload = $file;
if (isset($file_upload) && !empty($file_upload)){
//You can add directly the Composer Autoloder in your controller:
require FCPATH . 'vendor/autoload.php';
try{
$objPHPExcel = PHPExcel_IOFactory::load($file_upload);
}
catch (Exception $e){
die('Error loading file "' . pathinfo($file_upload, PATHINFO_BASENAME) . '": '.#$e->getMessage());
}
$allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestCol = $sheet->getHighestColumn();
$highestco = $sheet->getHighestDataColumn();
$arrayCount = count($allDataInSheet);
$now = date("Y-m-d H:i:s");
$flag = 0;
$check_template = array(
'A' => 'FIN_ID',
'B' => 'SECCODE',
'C' => 'SCHEME_NO',
'D' => 'SEC_SCH',
'E' => 'DISNO',
'F' => 'DISQTY',
'G' => 'BILLQTY',
'H' => 'BILLREF',
'I' => 'BILLDT',
);
$input_template = $allDataInSheet[1];
array_walk($input_template, $this->trim_value);
$result = array_diff($check_template, $input_template);
if(empty($result))
{
$this->srObject->truncTableDis();
# loop for inserting data
for ($i = 2,$j=0; $i <= $highestRow; $i++){
$db_ch_ot = 64;
$fin_id = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
$sec_code = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
$sch_no = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
$sec_sch = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
$dis_no = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
$dis_qty = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
$bill_qty = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
$bill_ref = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
$bill_dt = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
if(empty($bill_dt)){
$bill_dt = null;
}else{
$dip_dt = date("Y-m-d",strtotime($bill_dt));
}
$dt = date('Y-m-d H:i:s');
$insert_data = array(
"fin_id_data" => $fin_id,
"sec_code_data" => $sec_code,
"sch_no_data" => $sch_no,
"sec_sch_data" => $sec_sch,
"dis_no_data" => $dis_no,
"dis_qty_data" => $dis_qty,
"bill_qty_data" => $bill_qty,
"bill_ref_data" => $bill_ref,
"bill_dt_data" => $bill_dt,
"created_at_data" => $dt,
"updated_at_data" => $dt,
);
if($this->srObject->insertSdisData($insert_data))
{
++$flag;
}
} //loop close
} else {
$this->session->set_flashdata('error', 'Error. Invalid Excel Template');
redirect(site_url('schill-bill-checking-suuti/sreco'));
}
$this->session->set_flashdata('success', 'File Uploaded Successfully ..'.' New Record Inserted : '.$flag);
redirect(site_url('schill-bill-checking-suuti/sreco'));
}
}
function trim_value(&$value)
{
$value = trim($value);
}
// ut_sreco_dis Module
public function disExcelUpload($file=""){
ini_set('MAX_EXECUTION_TIME', -1);
ini_set('memory_limit', '-1');
$file_upload = $file;
if (isset($file_upload) && !empty($file_upload)){
//You can add directly the Composer Autoloder in your controller:
require FCPATH . 'vendor/autoload.php';
try{
$objPHPExcel = PHPExcel_IOFactory::load($file_upload);
}
catch (Exception $e){
die('Error loading file "' . pathinfo($file_upload, PATHINFO_BASENAME) . '": '.#$e->getMessage());
}
$allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestCol = $sheet->getHighestColumn();
$highestco = $sheet->getHighestDataColumn();
$arrayCount = count($allDataInSheet);
$now = date("Y-m-d H:i:s");
$flag = 0;
$check_template = array(
'A' => 'FIN_ID',
'B' => 'SECCODE',
'C' => 'SCHEME_NO',
'D' => 'SEC_SCH',
'E' => 'DISNO',
'F' => 'DISQTY',
'G' => 'BILLQTY',
'H' => 'BILLREF',
'I' => 'BILLDT',
);
$input_template = $allDataInSheet[1];
array_walk($input_template, $this->trim_value);
$result = array_diff($check_template, $input_template);
if(empty($result))
{
$this->srObject->truncTableDis();
# loop for inserting data
for ($i = 2,$j=0; $i <= $highestRow; $i++){
$db_ch_ot = 64;
$fin_id = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
$sec_code = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
$sch_no = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
$sec_sch = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
$dis_no = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
$dis_qty = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
$bill_qty = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
$bill_ref = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
$bill_dt = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
if(empty($bill_dt)){
$bill_dt = null;
}else{
$dip_dt = date("Y-m-d",strtotime($bill_dt));
}
$dt = date('Y-m-d H:i:s');
$insert_data = array(
"fin_id_data" => $fin_id,
"sec_code_data" => $sec_code,
"sch_no_data" => $sch_no,
"sec_sch_data" => $sec_sch,
"dis_no_data" => $dis_no,
"dis_qty_data" => $dis_qty,
"bill_qty_data" => $bill_qty,
"bill_ref_data" => $bill_ref,
"bill_dt_data" => $bill_dt,
"created_at_data" => $dt,
"updated_at_data" => $dt,
);
if($this->srObject->insertSdisData($insert_data))
{
++$flag;
}
} //loop close
} else {
$this->session->set_flashdata('error', 'Error. Invalid Excel Template');
redirect(site_url('schill-bill-checking-suuti/sreco'));
}
$this->session->set_flashdata('success', 'File Uploaded Successfully ..'.' New Record Inserted : '.$flag);
redirect(site_url('schill-bill-checking-suuti/sreco'));
}
}
function trimArray(&$value)
{
$value = trim($value);
}
$pmcArray = array('php ','mysql ', ' code ');
array_walk($pmcArray, 'trimArray');
by using array_walk function, we can remove space from array elements and elements return the result in same array.

Categories