Group by the array value - php

I'm using this code:
$permissions = array("canview", "canpostthreads", "canpostreplies", "canpostpolls", "all");
foreach($permissions as $permission) {
for ($i = 1; $i <= 5; $i++) {
$mode = $_POST['permission'][$i][$permission];
if($mode == 1)
echo "{$permission} = {$i}:::";
}
}
And the output if I check some checkboxes is:
canview = 1:::canview = 5:::canpostreplies = 3:::canpostpolls = 5:::
I wan't the output to be following:
instead of canview = 1:::canview = 5:
canview = 1,5
and if I'll have for example:
canpostpolls = 1:::canpostpolls = 2:::canpostpolls = 3
It'll be:
canpostpolls = 1,2,3:::canview = 1,5
I hope you understand it guys. This is my own idea for this, you are free to share your ideas with me, this data will be exported to the mysql table.

$permissions = array("canview", "canpostthreads", "canpostreplies", "canpostpolls", "all");
$setpermissions = array();
foreach($permissions as $permission) {
for ($i = 1; $i <= 5; $i++) {
$mode = $_POST['permission'][$i][$permission];
if($mode == 1) {
if (!isset($setpermissions[$permission])) {
$setpermissions[$permission] = array();
}
$setpermissions[$permission][] = $i;
}
}
}
$plist = array();
foreach ($setpermissions as $name => $sp) {
$plist[] = "$name = " . implode(',', $sp);
}
echo implode(':::', $plist);

You need to filter your data a bit more... maybe something like this:
$permissions = array("canview", "canpostthreads", "canpostreplies", "canpostpolls", "all");
$filtered_perms = array();
foreach($permissions as $permission) {
for ($i = 1; $i <= 5; $i++) {
$mode = $_POST['permission'][$i][$permission];
if($mode == 1) {
if(!is_array($filtered_perms[$permission])) {
$filtered_perms[$permission] = array();
}
$filtered_perms[$permission][] = $i;
}
}
Then, you can do something like:
$final_perms = array();
foreach($filtered_perms as $key => $val) {
$final_perms[$key] = implode(",", $val);
}
Hope that helps!

$permissions = array("canview", "canpostthreads", "canpostreplies", "canpostpolls", "all");
$userPermissions = array();
foreach($permissions as $permission) {
for ($i = 1; $i <= 5; $i++) {
$mode = $_POST['permission'][$i][$permission];
if($mode == 1)
$userPermissions[$permission][] = $i;
}
}
foreach($userPermissions as $permission => $values) {
echo "{$permission} = " . implode(',', $values) . ":::";
}

You can do something like this - essentially, combining the values before outputting them.
$permissions = array("canview", "canpostthreads", "canpostreplies", "canpostpolls", "all");
foreach($permissions as $permission) {
$vals = array();
for ($i = 1; $i <= 5; $i++) {
$mode = $_POST['permission'][$i][$permission];
if($mode == 1)
$vals[] = $i;
}
if(count($vals))
echo $permission . ' == ' . implode(',', $vals);
}

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;

Printing prime numbers from an user's input php

I'm trying ta make a program that will ask the user for a number and then show all the prime numbers between 0 to this number in an array.
<?php
class SmallerPrimes{
public function __construct($file){
$this->input_filename = $file;
}
public function Main(){
$smaller_than = (int)$this->readString()[0];
$result = array();
/* YOUR CODE HERE */
function isPrime($n)
{
if ($n <= 1)
return false;
for ($i = 2; $i < $n; $i++)
if ($n % $i == 0)
return false;
return true;
}
function printPrime($n)
{
for ($i = 2; $i <= $n; $i++)
{
if (isPrime($i))
echo $i . " ";
}
}
$n = 7;
printPrime($n);
/*end of your code here */
return $result;
}
public function readString(){
$file = fopen($this->input_filename, "r");
$line = array();
while (!feof($file)){
array_push($line, str_replace(PHP_EOL, "", fgets($file)));
}
return $line;
}
}
$o = new SmallerPrimes($argv[1]);
echo implode(" ", $o->Main()) . PHP_EOL;
This code work, but with a $n fixed.
I don't know how to use an input who ask the user a number
It's a code who verify itself and show us when it's ok
The code that i have to complete is this one (we only have this at first):
class SmallerPrimes{
public function __construct($file){
$this->input_filename = $file;
}
public function Main(){
$smaller_than = (int)$this->readString()[0];
$result = array();
/* YOUR CODE HERE */
return $result;
}
public function readString(){
$file = fopen($this->input_filename, "r");
$line = array();
while (!feof($file)){
array_push($line, str_replace(PHP_EOL, "", fgets($file)));
}
return $line;
}
}
$o = new SmallerPrimes($argv[1]);
echo implode(" ", $o->Main()) . PHP_EOL;
This is your script:
<?php
class SmallerPrimes{
public function __construct($file){
$this->input_filename = $file;
}
public function Main(){
$smaller_than = (int)$this->readString()[0];
$result = array();
function isPrime($n) {
if ($n <= 1) return false;
for ($i = 2; $i < $n; $i++) if ($n % $i == 0) return false;
return true;
}
function printPrime($n) {
for ($i = 2; $i < $n; $i++) if (isPrime($i)) $result[] = $i;
return $result;
}
$result = printPrime($smaller_than);
return $result;
}
public function readString(){
$file = fopen($this->input_filename, "r");
$line = array();
while (!feof($file)){
array_push($line, str_replace(PHP_EOL, "", fgets($file)));
}
return $line;
}}
$o = new SmallerPrimes($argv[1]);
echo implode(" ", $o->Main()) . PHP_EOL;
function getSmallerPrimes($smaller_than) {
if ($smaller_than <= 2) {
return [];
}
$result = [2];
$sqrt = sqrt($smaller_than);
for ($n = 3; $n < $smaller_than; $n += 2) {
$isPrime = true;
foreach($result as $prime) {
if ($n % $prime == 0) {
$isPrime = false;
break;
}
if ($prime > $sqrt) {
break;
}
}
if ($isPrime) {
$result[] = $n;
}
}
return $result;
}
$input = 23;
echo implode(' ', getSmallerPrimes($input));
Result: 2 3 5 7 11 13 17 19

how to use the for loop to extract data from a list of url using php

The for loop in the code below does not work properly.
$html= #file_get_html($url);
$job_array = array();
foreach($html->find('a') as $link) {
// $links=$html->find('a');
if (strpos($link->href, '/job-category/') !== false) {
$job_array[] = $link->href . "<br/>";
}
for ($a = 0; $a <= ($link->href); $a++) {
//$page_number = 20;
// for ($i = 1; $i <= $page_number; $i++) {
$html2 = file_get_html($link->href);
$response = array();
foreach ($html2->find('div#mainContent') as $header) {
$response[] = $header->innertext . "<br/>";
print_r($response);
}
}
I think
$link->href
isn't a number and the for loop can't use a non-number to compare $a to and iterate over. Perhaps you can do:
$html= #file_get_html($url);
$job_array = array();
$myNumberToIterateWith = 0;
foreach($html->find('a') as $link) {
// $links=$html->find('a');
$myNumberToIterateWith++;
if (strpos($link->href, '/job-category/') !== false) {
$job_array[] = $link->href . " ";
}
for ($a = 0; $a <= $myNumberToIterateWith; $a++) {
//$page_number = 20;
// for ($i = 1; $i <= $page_number; $i++) {
$html2 = file_get_html($link->href);
$response = array();
foreach ($html2->find('div#mainContent') as $header) {
$response[] = $header->innertext . "<br/>";
print_r($response);
}
}
Though I'm not sure what you wish the result to be. It is helpful to provide clues as to what you wish to accomplish with the code.

array_multisort how to mount with foreach

I need to mount an array_multisort with the values from one array.
I tryied to mount a string concated and call on the array_multidimensional like here:
function ordenar_matriz_ultima_posicion_por_distancia($matriz_up,$m_vehiculo_distancias){
$total_vehiculos=count($matriz_up[id_vehiculo]);
//resetear las keys de vehiculos para coger bien los kms y asignarlos
$a_vehiculo_distancia = array_values($m_vehiculo_distancias);
$ordenar = array();
foreach ($a_vehiculo_distancia as $key) {
$ordenar[] = $key;
}
sort($m_vehiculo_distancias);
$string= "";
$ultim_key = end(array_keys($matriz_up));
foreach ($matriz_up as $key => $valor) {
if ($key != $ultim_key) $string.= $matriz_up[$key].',';
else $string.= $matriz_up[$key];
$aaa = '$matriz_up[$key]';
}
echo $string;
echo "<br>";
array_multisort($ordenar, SORT_ASC, $string);
for($i=0;$i<$total_vehiculos;$i++){
$matriz_up['cercanos'][$i] = $m_vehiculo_distancias[$i];
echo $matriz_up['id_vehiculo'][$i]."<br>";
echo $matriz_up['fecha_gps'][$i]."<br>";
echo $matriz_up['id_tipo_posicion'][$i]."<br>";
echo $matriz_up['cercanos'][$i]."<br>";
echo $matriz_up['vaina'][$i]."<br>";
echo "------------<br>";
}
return $matriz_up;
}
$matriz_up['id_vehiculo'][0] = 9;
$matriz_up['fecha_gps'][0] = '2014';
$matriz_up['id_tipo_posicion'][0] = 11111;
$matriz_up['cercanos'][0] = 0;
$matriz_up['vaina'][0] = 12345;
$matriz_up['id_vehiculo'][1] = 3;
$matriz_up['fecha_gps'][1] = '2015';
$matriz_up['id_tipo_posicion'][1] = 22222;
$matriz_up['cercanos'][1] = 0;
$matriz_up['vaina'][1] = 5555;
$matriz_up['id_vehiculo'][2] = 1;
$matriz_up['fecha_gps'][2] = '2016';
$matriz_up['id_tipo_posicion'][2] = 33333;
$matriz_up['cercanos'][2] = 0;
$matriz_up['vaina'][2] = 988;
$matriz_up['id_vehiculo'][3] = 4;
$matriz_up['fecha_gps'][3] = '2017';
$matriz_up['id_tipo_posicion'][3] = 44444;
$matriz_up['cercanos'][3] = 0;
$matriz_up['vaina'][3] = 777;
$m_vehiculo_distancias[9] = 345;
$m_vehiculo_distancias[3] = 712;
$m_vehiculo_distancias[1] = 10;
$m_vehiculo_distancias[4] = 35;
ordenar_matriz_ultima_posicion_por_distancia($matriz_up,$m_vehiculo_distancias);
With this array_multisort works, but i need to take all the key without put manually..
array_multisort($ordenar, SORT_ASC, $matriz_up['id_vehiculo'], $matriz_up['fecha_gps'], $matriz_up['id_tipo_posicion'], $matriz_up['vaina'] );
Try this code:
<?php
$matriz_up = $m_vehiculo_distancias = array();
$matriz_up['id_vehiculo'][0] = 9;
$matriz_up['fecha_gps'][0] = '2014';
$matriz_up['id_tipo_posicion'][0] = 11111;
$matriz_up['cercanos'][0] = 0;
$matriz_up['vaina'][0] = 12345;
$matriz_up['id_vehiculo'][1] = 3;
$matriz_up['fecha_gps'][1] = '2015';
$matriz_up['id_tipo_posicion'][1] = 22222;
$matriz_up['cercanos'][1] = 0;
$matriz_up['vaina'][1] = 5555;
$matriz_up['id_vehiculo'][2] = 1;
$matriz_up['fecha_gps'][2] = '2016';
$matriz_up['id_tipo_posicion'][2] = 33333;
$matriz_up['cercanos'][2] = 0;
$matriz_up['vaina'][2] = 988;
$matriz_up['id_vehiculo'][3] = 4;
$matriz_up['fecha_gps'][3] = '2017';
$matriz_up['id_tipo_posicion'][3] = 44444;
$matriz_up['cercanos'][3] = 0;
$matriz_up['vaina'][3] = 777;
$m_vehiculo_distancias[9] = 345;
$m_vehiculo_distancias[3] = 712;
$m_vehiculo_distancias[1] = 10;
$m_vehiculo_distancias[4] = 35;
function sortArray($arrayToSortParam, $orderArray)
{
$result = array();
$arrayToSort = $arrayToSortParam;
$keys = array_keys($arrayToSort);
asort($orderArray, true);
$newSort = $cercanos = array();
foreach($orderArray as $key => $value)
{
$newSort[] = array_keys($arrayToSort['id_vehiculo'], $key)[0];
$cercanos[] = $orderArray[$key];
}
foreach($keys as $keyName)
{
uksort($arrayToSort[$keyName], function($key1, $key2) use ($newSort) {
return (array_search($key1, $newSort) > array_search($key2, $newSort));
});
}
$arrayToSort['cercanos'] = $cercanos;
//reset indexes
foreach($keys as $keyName)
{
$arrayToSort[$keyName] = array_values($arrayToSort[$keyName]);
}
return $arrayToSort;
}
echo '<pre>';
//print_r($matriz_up);
//print_r($m_vehiculo_distancias);
print_r(sortArray($matriz_up, $m_vehiculo_distancias)); //this is result
Working fiddle: CLICK!

where is mistake ? php letter matrix boggle

I find theese php codes here, but codes aren't working correctly. it seems that the if(isset($words[$word])) doesn't go through as I always get an empty results array
$boggle = "fxie
amlo
ewbx
astu";
$alphabet = str_split(str_replace(array("\n", " ", "\r"), "", strtolower($boggle)));
$rows = array_map('trim', explode("\n", $boggle));
$dictionary = file("C:/dict.txt");
$prefixes = array(''=>'');
$words = array();
$regex = '/[' . implode('', $alphabet) . ']{3,}$/S';
foreach($dictionary as $k=>$value) {
$value = trim(strtolower($value));
$length = strlen($value);
if(preg_match($regex, $value)) {
for($x = 0; $x < $length; $x++) {
$letter = substr($value, 0, $x+1);
if($letter == $value) {
$words[$value] = 1;
} else {
$prefixes[$letter] = 1;
}
}
}
}
$graph = array();
$chardict = array();
$positions = array();
$c = count($rows);
for($i = 0; $i < $c; $i++) {
$l = strlen($rows[$i]);
for($j = 0; $j < $l; $j++) {
$chardict[$i.','.$j] = $rows[$i][$j];
$children = array();
$pos = array(-1,0,1);
foreach($pos as $z) {
$xCoord = $z + $i;
if($xCoord < 0 || $xCoord >= count($rows)) {
continue;
}
$len = strlen($rows[0]);
foreach($pos as $w) {
$yCoord = $j + $w;
if(($yCoord < 0 || $yCoord >= $len) || ($z == 0 && $w == 0)) {
continue;
}
$children[] = array($xCoord, $yCoord);
}
}
$graph['None'][] = array($i, $j);
$graph[$i.','.$j] = $children;
}
}
function to_word($chardict, $prefix) {
$word = array();
foreach($prefix as $v) {
$word[] = $chardict[$v[0].','.$v[1]];
}
return implode("", $word);
}
function find_words($graph, $chardict, $position, $prefix, $prefixes, &$results, $words) {
$word = to_word($chardict, $prefix);
if(!isset($prefixes[$word])) return false;
**if(isset($words[$word])) {
$results[] = $word;
}**
foreach($graph[$position] as $child) {
if(!in_array($child, $prefix)) {
$newprefix = $prefix;
$newprefix[] = $child;
find_words($graph, $chardict, $child[0].','.$child[1], $newprefix, $prefixes, $results, $words);
}
}
}
$solution = array();
find_words($graph, $chardict, 'None', array(), $prefixes, $solution);
print_r($solution);
When you call find_words() at the end, you are only passing 6 parameters
find_words($graph, $chardict, 'None', array(), $prefixes, $solution);
The variable $words, is the 7th parameter in your definition of find_words()
function find_words($graph, $chardict, $position, $prefix, $prefixes, &$results, $words) {
Hence, $words will always be empty, and isset($words[$word]) will always be false

Categories