<?php
$str = '`&tpl = @FILE root / resources / mychank.tpl`';
// Вариант 1 (самый банальный)
$res_str = str_replace(' / ', '/', $str);
print_r($res_str);
// Вариант 2 (импровизация)
$res_str = implode('/', array_map('trim', explode('/', $str)));
print_r($res_str);
// Вариант 3 ( регулярка:) )
$res_str = preg_replace('#\s+/\s+#isu', '/', $str);
print_r($res_str);
Есть строка `&tpl = @FILE root / resources / mychank.tpl` в корой нужно удалит пробелы перед и после / с учетом того, что / должы находится в внутри `` которое содержит @FILE
Есть строка `&tpl = @FILE root / resources / mychank.tpl`
абракадабра / сым-салабым / чудо-юдо `&tpl = @FILE root / resources / mychank.tpl` / тырым-пырым / хали-гали
<?php
$str = 'абракадабра / `&tpl = @NOFILE root / resources / mychank.tpl` /сым-салабым / чудо-юдо `&tpl = @FILE root / resources / mychank.tpl` / тырым-пырым / хали-гали';
function trimSlashes($str) {
// Тут любой из вариантов, которые выше...в данном случае "взяли" третий, чтобы было всё на "регулярках" :)
return preg_replace('#\s+/\s+#isu', '/', $str[0]);
}
$res_str = preg_replace_callback('#`[^`]+@FILE[^`]+`#isu', 'trimSlashes', $str);
print_r($res_str);
<?php
$samples = [
123,
[1, 2, 3],
321
];
$samples_modified = [];
array_walk_recursive($samples, function ($item, $key) use (&$samples_modified) {
$samples_modified[] = $item;
});
print_r($samples_modified);
<?php
$samples = [
123,
[1, 2, 3],
321
];
$samples_modified = [];
function recursive_func($array){
global $samples_modified;
if(is_array($array)){
foreach($array as $below){
$res = recursive_func($below);
}
}else{
$samples_modified[] = $array;
}
return $samples_modified;
}
recursive_func($samples);
print_r($samples_modified);
For a PNG image, `setImageCompressionQuality()` is not work at all, length of the generated files are totally same.
But I found an effective way, that is use `setOption('png:compression-level', 9)`, the value range is 0-9.
class Polygon {
/**
* @var array
*/
var $polygon = [];
/**
* Polygon itself, with basic vector-based structure
* Array: [ [1,1], [2,1], [3,0], [2,-1] ]
*
* @var $polygon array
*/
function setPolygon($polygon) {
if (count($polygon) < 3) {
return false;
}
if (!isset($polygon[0]['x'])) {
foreach ($polygon as &$point) {
//$point = ['x' => round($point[0] + 300, 4), 'y' => round($point[1] + 300, 4)];
//$point = ['x' => round($point[0], 4), 'y' => round($point[1], 4)];
if($point[0] < 0)
$point[0] = 90 + 90 - abs($point[0]);
if($point[1] < 0)
$point[1] = 180 + 180 - abs($point[1]);
$point = ['x' => round($point[0], 4), 'y' => round($point[1], 4)];
}
}
$this->polygon = $polygon;
}
/**
* Check if $polygon contains $test value
*
* @var $test array(x=>decimal, y=>decimal)
*/
function calc($test) {
if($test['x'] < 0)
$test['x'] = 90 + 90 - abs($test['x']);
if($test['y'] < 0)
$test['y'] = 180 + 180 - abs($test['y']);
$q_patt= [[0, 1], [3, 2]];
$end = end($this->polygon);
$pred_pt = end($this->polygon);
$pred_pt['x'] -= $test['x'];
$pred_pt['y'] -= $test['y'];
$pred_q = $q_patt[$pred_pt['y'] < 0][$pred_pt['x'] < 0];
$w = 0;
for ($iter = reset($this->polygon); $iter !== false; $iter = next($this->polygon)) {
$cur_pt = $iter;
$cur_pt['x'] -= $test['x'];
$cur_pt['y'] -= $test['y'];
$q = $q_patt[$cur_pt['y'] < 0][$cur_pt['x'] < 0];
switch ($q - $pred_q) {
case -3:
++$w;
break;
case 3:
--$w;
break;
case -2:
if ($pred_pt['x'] * $cur_pt['y'] >= $pred_pt['y'] * $cur_pt['x']) {
++$w;
}
break;
case 2:
if (!($pred_pt['x'] * $cur_pt['y'] >= $pred_pt['y'] * $cur_pt['x'])) {
--$w;
}
break;
}
$pred_pt = $cur_pt;
$pred_q = $q;
}
return $w != 0;
}
public static function distance($lat1, $lng1, $lat2, $lng2) {
$lat1=deg2rad($lat1);
$lng1=deg2rad($lng1);
$lat2=deg2rad($lat2);
$lng2=deg2rad($lng2);
$delta_lat=($lat2 - $lat1);
$delta_lng=($lng2 - $lng1);
return round( 6378137 * acos( cos( $lat1 ) * cos( $lat2 ) * cos( $lng1 - $lng2 ) + sin( $lat1 ) * sin( $lat2 ) ) );
}
public static function closestPoint($x, $y, $arPoints) {
$RESULT = false;
$x = floatval($x);
$y = floatval($y);
if(!empty($arPoints) && is_array($arPoints) && count($arPoints) > 0) {
$arRes = array();
foreach ($arPoints as $KEY => $VAL) {
$x2 = floatval($VAL[0]);
$y2 = floatval($VAL[1]);
$distance = self::distance($x, $y, $x2, $y2);
$arRes[$KEY] = $distance;
}
if(count($arRes) > 0) {
natsort($arRes);
reset($arRes);
//$RESULT[key($arRes)] = current($arRes);
$RESULT = array(
'ID' => key($arRes),
'DISTANCE' => current($arRes)
);
}
}
return $RESULT;
}
}
/* Ипользование */
// Координаты точки, которую проверяем на вхождение в "полигон"
$X = 33.45;
$Y = 44.25;
// "Полигоны"
$arCheckPoints = [
'КЛЮЧ_МНОГОУГОЛЬНИКА' => [22.45, 44.55, 11.22, 55.66], // Координаты вершин
'КЛЮЧ_МНОГОУГОЛЬНИКА_2' => [33.45, 66.55, 77.22, 99.66], // Координаты вершин
'КЛЮЧ_МНОГОУГОЛЬНИКА_3' => [12.45, 15.55, 17.22, 54.66], // Координаты вершин
];
$arResults = [];
$p = new \App\Helpers\Polygon();
foreach ($arCheckPoints as $KEY_POLYGON => $arPolygon) {
$p->setPolygon($arPolygon);
if($p->calc(array('x' => $X, 'y' => $Y)))
$arResults[$KEY_POLYGON] = $arPolygon;
}
class Order extends Model
{
// ... Тут стандартное начало модели
protected $appends = [
'status_color'
];
public function getStatusColorAttribute() {
switch($this->status) {
case 1:
return 'зелёный';
break;
case 2:
return 'синий';
break;
case 3:
return 'красный';
break;
default:
return 'хз';
break;
}
}
}
CREATE TABLE `test` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`count` int(11) NOT NULL DEFAULT 0,
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `test` (`name`) VALUES ('строка')
ON DUPLICATE KEY
UPDATE `count` = `count` + 1;
Можно например использовать Redis (increment)...
Где ключ будет "строка" (в данном случае kot например).
Перед записью ныряем в Redis, подкручиваем "счётчик" и далее берем это значение и записываем в MySQL в поле slug:
kot-ЗНАЧНИЕ_СЧЁТЧИКА
В итоге один запрос в Redis и один INSERT в MySQL...
Понятна мысля?)
P.S.: Redis можно и на MySQL тож заменить...используя мой первый вариант в ответе в качестве счётчика вместо Redis'а...но тут на пару запросов больше выйдет...что и не критично в данном случае думаю...
<?php
$from_id = $items->pluck('from_id');
$arFormIds = $from_id->toArray();
$arPlus = $from_id->where($arFormIds, function ($value, $key) {
return $value > 0;
})->toArray();
$arMinus = $from_id->where($arFormIds, function ($value, $key) {
return $value < 0;
})->toArray();
// $arPlus - все положительные
// $arMinus - все отрицательные
?>
<?php
// $items - твоя коллекция...без pluck...
$arPlus = $items->where('form_id', '>', 0)->toArray();
$arMinus = $items->where('form_id', '<', 0)->toArray();
// $arPlus - все положительные
// $arMinus - все отрицательные
?>
Получили $_POST массив [12, 119, 6, 9]
SELECT `id`, `value`
FROM `table`
ORDER BY
CASE `id`
WHEN 12 then 1
WHEN 119 then 2
WHEN 6 then 3
WHEN 9 then 4
ELSE NULL
END
ASC
SELECT `id`, `value`
FROM `table`
WHERE `id` IN(12,119,6,9)
ORDER BY
CASE `id`
WHEN 12 then 1
WHEN 119 then 2
WHEN 6 then 3
WHEN 9 then 4
ELSE NULL
END
ASC
Делаю админку. Вывожу список значений из таблицы в порядке `id`.
Использую jquery-UI sortable. Можно переставлять местами строки и отправить форму.
foreach($base AS $row) {
$result[] = $row;
// var_dump($result); // Раскомментируй, чтобы понять "почему"
}
foreach($base AS $row) {
$result[] = trim($row);
// var_dump($result); // Раскомментируй, чтобы понять "почему"
}