Skip to content

Instantly share code, notes, and snippets.

@PandCar
Last active April 6, 2020 14:00
Show Gist options
  • Save PandCar/6cfec598ec12c412bb448e1a107ca0b6 to your computer and use it in GitHub Desktop.
Save PandCar/6cfec598ec12c412bb448e1a107ca0b6 to your computer and use it in GitHub Desktop.
<?php
/**
* @author Oleg Isaev (PandCar)
* @contacts vk.com/id50416641, t.me/pandcar, github.com/pandcar
*/
$arr = [
[
'key' => 3,
'selected' => 0,
'value' => 'Baccalaureate',
],
[
'key' => 1,
'selected' => 2,
'value' => 'Ffvcdcc 3 ff',
],
[
'key' => 2,
'selected' => 1,
'value' => 'fsdg sdd',
],
];
// Выборка из массива
$res = array_select($arr, [
['key', '>', 0],
['value', 'regexp', '^Ffv'],
], true);
// Сортировка результата
$res = array_order($res, ['key' => 'desc']);
print_r($res);
function array_select($arr, $select_and, $all = false)
{
if (! is_array($arr) || empty($select_and)) {
return false;
}
$ret = [];
foreach ($arr as $row)
{
$bools = [];
foreach ($select_and as $and)
{
list($key, $op, $val) = $and;
$vrow = $row[ $key ];
if ($op == '=') {
$bools []= ($vrow == $val);
} elseif ($op == '!=') {
$bools []= ($vrow != $val);
} elseif ($op == '>') {
$bools []= ($vrow > $val);
} elseif ($op == '<') {
$bools []= ($vrow < $val);
} elseif ($op == '>=') {
$bools []= ($vrow >= $val);
} elseif ($op == '<=') {
$bools []= ($vrow <= $val);
} elseif ($op == 'regexp') {
preg_match('~'.$val.'~isu', $vrow, $preg);
$bools []= ! empty($preg);
}
}
if (in_array(false, $bools, true) === false)
{
$ret []= $row;
if (! $all) {
break;
}
}
}
if (empty($ret)) {
return ! $all ? false : [];
}
return ! $all ? $ret[0] : $ret;
}
function array_order($array, $order_by, $save_keys = false)
{
$sort_opt = function($a, $b) use ($order_by) {
$res = 0;
foreach ($order_by as $k => $v)
{
if ($a[$k] == $b[$k]) {
continue;
}
$res = ($a[$k] < $b[$k] ? -1 : 1);
if (strtolower($v) == 'desc') {
$res = -$res;
}
break;
}
return $res;
};
if ($save_keys) {
uasort($array, $sort_opt);
} else {
usort($array, $sort_opt);
}
return $array;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment