Ascending order of fetched data - codeigniter

I am fetching count. My target is to display it in ASCENDING ORDER. i have tried to sort it using sort($match); but i have still failed to achieve my goal. Thank you. Any help will be appreciated
Controller:
function asdasdas(){
$entry= $this->repo->entryfetch();
$data='<table>
<thead><tr><th>NO. </th></tr></thead>';
foreach($entry as $entry){
$match= $this->repo->matchfetch($entry->handlerID);
$data.='<thead><tr><th><hr>'.$entry->handlerID.' '.$entry->entryName.'</th> ';
foreach($match as $match){
$diff = $match->weightM - $match->weightW;
if($match->handlerIDM === $entry->handlerID){
$name=$match->handlertestW;
$count=$match->countM;
}else{
$name=$match->handlerM;
$count=$match->countW;
}
$data.='<tbody><tr><td>'.$count.'</td>';
$data.='<td></td></tr></tbody>';
//
}
}
$data .='<table>';
echo $data;
sort($match); // i have tried to sort it using this but it is not working.
}

You can loop the array from the last index to 0
function asdasdas()
{
$entry = $this->repo->entryfetch();
$data = '<table>
<thead><tr><th>NO. </th></tr></thead>';
for ($j = count($entry) - 1; $j >= 0; $j--) {
$match = $this->repo->matchfetch($entry[$j]->handlerID);
$data .= '<thead><tr><th><hr>' . $entry[$j]->handlerID . ' ' . $entry[$j]->entryName . '</th> ';
for ($i = count($match) - 1; $i >= 0; $i--) {
$diff = $match[$i]->weightM - $match[$i]->weightW;
if ($match[$i]->handlerIDM === $entry[$j]->handlerID) {
$name = $match[$i]->handlertestW;
$count = $match[$i]->countM;
} else {
$name = $match[$i]->handlerM;
$count = $match[$i]->countW;
}
$data .= '<tbody><tr><td>' . $count . '</td>';
$data .= '<td></td></tr></tbody>';
}
}
$data .= '<table>';
echo $data;
}

Context is not much clear. Do you need to sort $match before for loop or while inside the forloop. Can you explain a bit if haven't got the solution.

Related

Custom chunk implementation

Is it possible to customize the chunk configuration in Filepond such that the chunk information is provided to the upload server:
as query parameters instead of headers
with custom query parameter names instead of Upload-Length, Upload-Name, and Upload-Offset
I am trying to fit Filepond's chunk implementation to a third party upload endpoint that I don't have control over.
I have found the Advanced configuration where you provide a process function which I've played with a little bit to see what comes through the options param -- however that appears (I think) to make the chunking calculations my responsibility. My original thought was to manipulate the options.chunkServer.url to include the query params I need but I don't believe this processes individual chunks.
In case it makes a difference, this is being done in React using the react-filepond package.
I made and implementation in Laravel 6 using Traits and some "bad practices" (I didn't have time because ... release in prod) to join chunks into a file
Basically:
post to get unique id folder to storage
get chunks and join together
profit!
Here's the full code:
<?php
namespace App\Http\Traits\Upload;
use Closure;
use Faker\Factory as Faker;
use Illuminate\Http\Request;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
trait Uploadeable
{
public function uploadFileInStorage(Request $request, Closure $closure)
{
// get the nex offset for next chunk send
if (($request->isMethod('options') || $request->isMethod('head')) && $request->has('patch')) {
//get the temp dir
$dir = $request->patch . DIRECTORY_SEPARATOR;
// reead all chunks in directory
$patch = collect(Storage::files($dir))
->sortBy(function ($file) {
return Storage::lastModified($file);
});
// read offsets for calculate
$offsets = array();
$size = 0;
$last_offset = 0;
foreach ($patch as $filename) {
$size = Storage::size($filename);
list($dir, $offset) = explode('file.patch.', $filename, 2);
array_push($offsets, $offset);
if ($offset > 0 && !in_array($offset - $size, $offsets)) {
$last_offset = $offset - $size;
break;
}
// last offset is at least next offset
$last_offset = $offset + $size;
}
// return offset
return response($last_offset, 200)
->header('Upload-Offset', $last_offset);
}
// chunks
if ($request->isMethod('patch') && $request->has('patch')) {
// get the temp dir
$dir = $request->patch . DIRECTORY_SEPARATOR;
// read headers
$offset = $request->header('upload-offset');
$length = $request->header('upload-length');
// should be numeric values, else exit
if (!is_numeric($offset) || !is_numeric($length)) {
return response('', 400);
}
// get the file name
$name = $request->header('Upload-Name');
// sleep server for get a diference between file created to sort
usleep(500000);
// storage the chunk with name + offset
Storage::put($dir . 'file.patch.' . $offset, $request->getContent());
// calculate total size of patches
$size = 0;
$patch = Storage::files($dir);
foreach ($patch as $filename) {
$size += Storage::size($filename);
}
// make the final file
if ($size == $length) {
// read all chunks in directory
$files = collect(Storage::files($dir))
->sortBy(function ($file) {
return Storage::lastModified($file);
});
// create output file
//Log::info(storage_path('app'));
$new_file_name = $final_name = trim(storage_path('app') . DIRECTORY_SEPARATOR . $dir . $name);
$file_handle = fopen($new_file_name, 'w');
// write patches to file
foreach ($files as $filename) {
// get offset from filename
list($dir, $offset) = explode('.patch.', $filename, 2);
// read chunk
$patch_handle = fopen(storage_path('app') . DIRECTORY_SEPARATOR . trim($filename), 'r');
$patch_contents = fread($patch_handle, filesize(storage_path('app') . DIRECTORY_SEPARATOR . trim($filename)));
fclose($patch_handle);
// apply patch
fseek($file_handle, $offset);
fwrite($file_handle, $patch_contents);
}
// done with file
fclose($file_handle);
// file permission (prefered 0755)
chmod($final_name, 0777);
// remove patches
foreach ($patch as $filename) {
$new_file_name = storage_path('app') . DIRECTORY_SEPARATOR . trim($filename);
unlink($new_file_name);
}
// simple class (no time to explain)
$file = new UploadedFile(
$final_name,
basename($final_name),
mime_content_type($final_name),
filesize($final_name),
false
);
$dir = $request->patch . DIRECTORY_SEPARATOR;
$object = new \stdClass();
$object->full_path = (string)$file->getPathname();
$object->directory = (string)($dir);
$object->path = (string)($dir . basename($final_name));
$object->name = (string)$file->getClientOriginalName();
$object->mime_type = (string)$file->getClientMimeType();
$object->extension = (string)$file->getExtension();
$object->size = (string)$this->formatSizeUnits($file->getSize());
// exec closure
$closure($file, (object)$object, $request);
}
// response
return response()->json([
'message' => 'Archivo subido correctamente.',
'filename' => $name
], 200);
}
// get dir unique id folder temp
if ($request->isMethod('post')) {
$faker = Faker::create();
$unique_id = $faker->uuid . '-' . time();
$unique_folder_path = $unique_id;
// create directory
Storage::makeDirectory($unique_folder_path);
// permisos directorio
chmod(storage_path('app') . DIRECTORY_SEPARATOR . $unique_folder_path . DIRECTORY_SEPARATOR, 0777);
// response with folder
return response($unique_id, 200)
->header('Content-Type', 'text/plain');
}
}
private function formatSizeUnits($bytes)
{
if ($bytes >= 1073741824) {
$bytes = number_format($bytes / 1073741824, 2) . ' GB';
} elseif ($bytes >= 1048576) {
$bytes = number_format($bytes / 1048576, 2) . ' MB';
} elseif ($bytes >= 1024) {
$bytes = number_format($bytes / 1024, 2) . ' KB';
} elseif ($bytes > 1) {
$bytes = $bytes . ' bytes';
} elseif ($bytes == 1) {
$bytes = $bytes . ' byte';
} else {
$bytes = '0 bytes';
}
return $bytes;
}
}
ยดยดยด

How to pluck a value from foreach statement in Laravel

I am getting an array from database table and through a for each statement. Then check the difference between two values if there is any difference that is less than zero sets a value to 0 for that loop. Then do the same with the next loop.
$bom_id = App\Models\Bom::where('item_id', $item->order_item->id)->pluck('id')->first();
if ($bom_id > 0) {
$bomList = App\Models\Bom_list::where('bom_id', $bom_id)->get();
echo '<div class="row">';
foreach ($bomList as $bomlist) {
$availableQty = $item->order_item->qty;
$requiredQty = $bomlist->qty * $item->qty;
$dif = $availableQty - $requiredQty;
}
$check = '';
$arr = array($bomlist->$dif);
$light = in_array($check, $arr, true) ? 0 : 1;
} else {
$light = 0;
}
enter image description here

laravel - foreach repeat many times

I have two model : User & Book. I want create a book for each user with a specific QR code
$users = User::get();
$date = ... ;
$finalCount = 0;
$code = 150;
$userCount = count($users);
foreach ($users as $user) {
$book = new Book();
$book->unique_id = uniqid('', true);
$book->user_id = $user->unique_id;
$book->code = "PP-" . strval(mt_rand(100, 999)) . strval($code);
$book->create_date = $date;
$book->status = 'active';
$book->save();
$QRCode = new BaconQrCodeGenerator;
$file = public_path('/images/book/' . $book->code . '.png');
$QRCode->encoding('UTF-8')
->format('png')
->merge('/public/image/logo.png', .15)
->size(1000)
->generate($book->unique_id, $file);
if (File::exists($file))
$finalCount++;
$code++;
if ($finalCount == $userCount)
break;
}
After this function called, i have 20 book for each user. I used an if statement for break the loop ( if ($finalCount == $userCount) ) but it doesn't work.
I can't understand whats going on here and also i have not any error log
Instead of
$file = public_path('/images/book/' . $book->code . '.png');
try
$file = public_path().'/images/book/' . $book->code . '.png';

Logical algorithm to generate paths

I'm trying to develop an algorithm to create a symfony template service.
I want to check if a template exists in a subset of paths, ordered.
Given an array of parameter like this (already ordered like I want):
$params = ['O', 'U', 'W', 'P']
How can I output this array?
$urls = [
'O/U/W/P/template',
'O/U/W/template',
'O/U/P/template',
'O/U/template',
'O/W/P/template',
'O/W/template',
'O/P/template',
'O/template',
'U/W/P/template',
'U/W/template',
'U/P/template',
'U/template',
'W/P/template',
'W/template',
'P/template',
'template'
];
I can perform for a little list of parameters (like everyone can do it I suppose) with a code like this :
private function getPaths($template, $params)
{
$urls = [];
$alreadyPerform = [];
$paramsCounter = count($params);
for ($i = 0; $i < $paramsCounter; $i++) {
for ($j = 0; $j < $paramsCounter; $j++) {
if ($i !== $j && !in_array($params[$j], $alreadyPerform, true)) {
$urls[] = sprintf(
'/%s/%s/%s.html.twig', $params[$i], $params[$j], $template
);
}
}
$alreadyPerform[] = $params[$i];
$urls[] = sprintf('/%s/%s.html.twig', $params[$i], $template);
}
$urls[] = sprintf('%s.html.twig', $template);
return $urls;
}
This function work like I wanted until today (max 3 parameters), but I want to add one parameters today, maybe more after.
Thank you very much for your help !
Cheers.
Using recursion, you can do the following:
/**
* #param array $elements
* #param array $extra
*
* #return Generator
*/
function gen(array $elements, array $extra = []): \Generator {
foreach ($elements as $i => $head) {
foreach (gen(array_slice($elements, $i + 1), $extra) as $tail) {
yield array_merge([$head], $tail);
}
}
yield $extra;
}
demo: https://3v4l.org/gJB8q
Or without recursion:
/**
* #param array $elements
*
* #return Generator
*/
function gen2(array $elements): \Generator {
for ($num = count($elements), $i = pow(2, $num) - 1; $i >= 1; $i -= 2) {
$r = [];
for ($j = 0; $j < $num; $j += 1) {
if ($i & (1 << ($num - $j - 1))) {
$r[] = $elements[$j];
}
}
yield $r;
}
}
demo: https://3v4l.org/grKXo
Consider using the following package:
https://github.com/drupol/phpermutations
Just a very basic example of what it can do:
$permutations = new \drupol\phpermutations\Generators\Permutations(['A', 'B', 'C'], 2);
foreach ($permutations->generator() as $permutation) {
echo implode('/', $permutation);
echo "\n";
}
A/B
B/A
A/C
C/A
B/C
C/B

Unink log files that were created the day before in codeigniter

I am trying to unlink files that were created the day before
I have a custom application > core > MY_Log.php file and it creates a log for each error level. For easier reading.
logs > DEBUG-04-08-2016.php
logs > ERROR-04-08-2016.php
logs > INFO-04-08-2016.php
logs > DEBUG-03-08-2016.php
logs > ERROR-03-08-2016.php
logs > INFO-03-08-2016.php
Question how am I able to modify the write_log so could delete / unlink files that were created the day before?
<?php
class MY_Log extends CI_Log {
public function write_log($level, $msg)
{
if ($this->_enabled === FALSE)
{
return FALSE;
}
$level = strtoupper($level);
if (( ! isset($this->_levels[$level]) OR ($this->_levels[$level] > $this->_threshold))
&& ! isset($this->_threshold_array[$this->_levels[$level]]))
{
return FALSE;
}
$filepath = $this->_log_path . $level .'-'. date('d-m-Y').'.'.$this->_file_ext;
$message = '';
if ( ! file_exists($filepath))
{
$newfile = TRUE;
// Only add protection to php files
if ($this->_file_ext === 'php')
{
$message .= "";
}
}
if ( ! $fp = #fopen($filepath, 'ab'))
{
return FALSE;
}
flock($fp, LOCK_EX);
// Instantiating DateTime with microseconds appended to initial date is needed for proper support of this format
if (strpos($this->_date_fmt, 'u') !== FALSE)
{
$microtime_full = microtime(TRUE);
$microtime_short = sprintf("%06d", ($microtime_full - floor($microtime_full)) * 1000000);
$date = new DateTime(date('d-m-Y H:i:s.'.$microtime_short, $microtime_full));
$date = $date->format($this->_date_fmt);
}
else
{
$date = date($this->_date_fmt);
}
$message .= $this->_format_line($level, $date, $msg);
for ($written = 0, $length = strlen($message); $written < $length; $written += $result)
{
if (($result = fwrite($fp, substr($message, $written))) === FALSE)
{
break;
}
}
flock($fp, LOCK_UN);
fclose($fp);
if (isset($newfile) && $newfile === TRUE)
{
chmod($filepath, $this->_file_permissions);
}
return is_int($result);
}
}
First of use
$config['log_threshold'] = 1;
For only error message, so there will be less number of files
Add below code just before $filepath; to delete previous date logs
$unlink_date = date('Y-m-d',strtotime("-1 days"));
$filepath_unlink = $this->_log_path . $level .'-'. $unlink_date.'.'.$this->_file_ext;
if ( file_exists($filepath_unlink))
{
unlink($filepath_unlink);
}

Resources