Filing or balancing array with dynamic generated index and values - php

Basically I want to balance an array.
The array I want to balance is retrieved from DB and can be unknown
Here is sample array retrieved from DB, it can vary
<?php
$arr_from_DB = array(
'1'=>NULL,
'2'=>1,
'3'=>1,
);
$node_width_from_DB = 3;
$node_depth_from_DB = 2;
?>
//Max Capacity was caclulated from $node_width_from_DB, $node_depth_from_DB AND WAS ALSO SAVED in DB , simulated below for width = 3 , depth = 2
$max_cap_of_array = 13;
//With $arr_from_DB fed to the display fxn on frontend, this is the result
//What I want to achieve, I want to transform $arr_from_DB to below ARray, All Array index with negative is seen to be dynamically generated
<?php
$formated_arr = array(
'1'=>NULL,
'2'=>1,
'3'=>1,
'-1'=>1,
'-2'=>2,
'-3'=>2,
'-4'=>2,
'-5'=>3,
'-6'=>3,
'-7'=>3,
'-8'=>-1,
'-9'=>-1,
'-10'=>-1,
);
?>
//With $formated_arr fed to the display fxn on frontend, this is the result
WHAT I TRIED SO FAR
<?php
$arr_filled = RECfillMissingDownlineArr($arr_from_DB);
var_dump($arr_filled);
function RECfillMissingDownlineArr($selectedArr, $pointer=1){
$node_width_from_DB = 3;
$node_depth_from_DB = 2;
//Max Capacity was caclulated from $node_width_from_DB, $node_depth_from_DB AND WAS ALSO SAVED in DB , simulated below for width = 3 , depth = 2
$max_cap_of_array = 13;
//var_dump($Allarr);
if($pointer>= $max_cap_of_array){
return $selectedArr;
}
$array_worked = array_count_values($selectedArr);
$array_worked3 = array_keys($selectedArr);
$array_worked2 = array_values($array_worked3);
//$key_p = $array_worked3[$pointer];
foreach($array_worked as $key=>$value){
//echo 'Value nm'.$value.'<br>';
if($value<$node_width_from_DB){
$key_p = $key;
break;
}
}
$array_worked1 = array_keys($selectedArr, $key_p);
for ($i=0; $i <$width ; $i++) {
if(empty($array_worked1[$i])){
$key_pointer = $pointer * -1;
$selectedArr[$key_pointer] = $key;
$pointer++;
return RECfillMissingDownlineArr($selectedArr,$pointer);
}
}
}
OUTPUT NULL, It's not what I want, it's returning null alltogether
?>

Related

Why do I get an array in response after calling an array value by key

I call a function, and I want to get a response with an array and two elements per key.
include_once($_SERVER['DOCUMENT_ROOT'].'/matsuka/_giveRandomQuestSearchPok.php');
$pokQ = QuestPoks::giveRandomQuestPok();
The function itself looks like this
public static function giveRandomQuestPok() {
$sC = \Work::$sql->prepare('SELECT region FROM users WHERE id = ?');
$sC->bind_param("i", $_SESSION['id']);
$sC->execute();
$dA = $sC->get_result();
$region = $dA->fetch_assoc();
if($region['region'] == 1){
include_once($_SERVER['DOCUMENT_ROOT'].'/matsuka/randomPoks/Kanto.php');
}elseif($region['region'] == 3){
include_once($_SERVER['DOCUMENT_ROOT'].'/matsuka/randomPoks/Hoenn.php');
}
$rarity = mt_rand(1,100);
if($rarity == 1){
$rare = 1;
$object = \matsuka\Rare[mt_rand(0, count(\matsuka\Rare) - 1)];
}elseif($rarity > 1 && $rarity <= 33){
$rare = 2;
$object = \matsuka\Uncommon[mt_rand(0, count(\matsuka\Uncommon) - 1)];
}else{
$rare = 3;
$object = \matsuka\Common[mt_rand(0, count(\matsuka\Common) - 1)];
}
$array = array();
$array['pok'] = $object;
$array['rare'] = $rare;
return $array;
}
After executing the function I want to assign two variables to control the result
$pok = $pokQ["pok"];
$rare = $pokQ["rare"];
But the handler still reads them as an array.
And when I paste it into sql I get an Array, although I was hoping to get the array data by their corresponding key.
In var_dump I get quite a strange answer. I seem to see the required value of array called by the key, but on top of that I see another array, if I understand correctly.
int(401)
{
"name":"\u0413\u0443\u0441\u0442\u0430\u0432",
"actionQuest":"<img src=\"\/img\/quests\/7.webp\" class=\"quest\"> \u041e\u0431\u043d\u043e\u0432\u043b\u0435\u043d\u0430 \u0438\u043d\u0444\u043e\u0440\u043c\u0430\u0446\u0438\u044f \u0432 \u0437\u0430\u0434\u0430\u043d\u0438\u0438 \u00ab\u041f\u043e\u043c\u043e\u0449\u044c \u0441\u0442\u0430\u0440\u043e\u043c\u0443 \u043f\u0440\u0438\u044f\u0442\u0435\u043b\u044e\u00bb. \u0417\u0430\u0433\u043b\u044f\u043d\u0438\u0442\u0435 \u0432 \u0410\u043a\u0432\u0430\u0431\u0443\u043a.",
"question":"\u0422\u044b \u043e\u0442\u043b\u0438\u0447\u043d\u043e \u0441\u043f\u0440\u0430\u0432\u0438\u043b\u0441\u044f \u0441 \u043c\u043e\u0438\u043c \u043f\u0440\u043e\u0448\u043b\u044b\u043c \u0437\u0430\u0434\u0430\u043d\u0438\u0435\u043c. \u042f \u0445\u043e\u0440\u043e\u0448\u0435\u043d\u044c\u043a\u043e \u0438\u0437\u0443\u0447\u0438\u043b \u0442\u043e\u0433\u043e \u043f\u043e\u043a\u0435\u043c\u043e\u043d\u0430. \u0422\u0435\u043f\u0435\u0440\u044c \u043c\u043d\u0435 \u043d\u0443\u0436\u0435\u043d: <div class=\"questPokemon\"><img src=\"\/img\/pokemons\/mini\/normal\/Array.webp\"> <div>#Array <\/div><\/div>"
}
Why does this happen and what is my mistake?
In the array I should only get 3-digit numbers under each key

Fetching latest value from database even when there are no rows present

So I'm trying to fetch a points table for users to add points in by garnering their total points and adding it with the installation points, however by trying to fetch their "latest" points, new users who do not have an existing row in the table will throwback an error "InvalidArgumentException; Data Missing". This would be my code below, and are there any other ways around this?
$currentpoint = Points::where('user_id', $input['user_id'])->latest()->first();
$points['user_id'] = $input['user_id'];
$points['points_add'] = $battery['point_installation'];
$points['points_subtract'] = 0;
$points['points_total'] = $currentpoint + $battery['point_installation'];
$points['points_source_id'] = 1;
$points['created_at'] = $mytime;
$points['updated_at'] = $mytime;
$point = Points::create($points);
$currentpoint = Points::where('user_id', $input['user_id'])->latest()->first(); of your code return an object and you are try to perform math (addition) operation on that object which is not possible. You can update your code like below.
$currentpoint = Points::where('user_id', $input['user_id'])->latest()->first();
$points['user_id'] = $input['user_id'];
$points['points_add'] = $battery['point_installation'];
$points['points_subtract'] = 0;
if($currentpoint != null)
{
$points['points_total'] = $currentpoint->points_total + $battery['point_installation'];
}
else {
$points['points_total'] = $battery['point_installation'];
}
$points['points_source_id'] = 1;
$points['created_at'] = $mytime;
$points['updated_at'] = $mytime;
$point = Points::create($points);

Get all data with owner = value From json code with php

i want get all objects with owner = true
i have made code that get specific data from json array
so when i print id to find it give me the last one i want it print all owner value = true
i did try foreach but give me error
so any one can help me
{
"owner":true,
"number":2146958847,
"ser":"333",
"id":"505417057861500987",
"name":" test"
},
{
"owner":true,
"number":2146958847,
"ser":null,
"id":"506154122521608196",
"name":"test1"
}
]
my code
<?php $o1 = json_encode($_SESSION['guilds']);
$arr = json_decode($o1,true);
$username = array();
$len = count($arr);
for($i = 0; $i < $len; $i++){
$id = $arr[$i]["id"];
$owner = $arr[$i]["owner"];
$isowner[$owner] = $id;
}
$thisisowner = true;
if(isset($isowner[$thisisowner]) ){
$idToFind = $isowner[$thisisowner];
echo $idToFind;
}else{
echo "this owner doesn't exist";
}
?>
output for this code = 505417057861500987
i want to be like this =
id: 505417057861500987 - Number : 2146958847 | name : test1 ,id : 506154122521608196 | Number : 2146958847| name : test
not one

Weighted Load Balancing Algorithm into PHP Application

I want to resolve weighted an Adapter from an factory which could be configured by user (enable/disable and weight %).
Example:
AdapterW ≃ 20% of transaction
AdapterX ≃ 30% of transaction
AdapterY ≃ 40% of transaction
AdapterZ ≃ 10% of transaction
I can grant that all items will never sum more than one hundred (100%), but sometimes any adapter could be deactivated.
I have the following parameters:
public function handleAdapter()
{
$isWActive = (boolean)$this->_config[self::W];
$isXActive = (boolean)$this->_config[self::X];
$isYActive = (boolean)$this->_config[self::Y];
$isZActive = (boolean)$this->_config[self::Z];
$WPercentage = (int)$this->_config[self::LOAD_BALANCE_W];
$XPercentage = (int)$this->_config[self::LOAD_BALANCE_X];
$YPercentage = (int)$this->_config[self::LOAD_BALANCE_Y];
$ZPercentage = (int)$this->_config[self::LOAD_BALANCE_Z];
.
.
.
return (self::W | self::X | self::Y | self::Z);
}
How can i balance weighted between this adapters dynamically?
Edit
created a gist to a executable code: https://gist.github.com/markomafs/5d892d06d6670909f9b4
This may not be the best approach, but you can try something like this:
public function handleAdapter()
{
//an array to return the balanced entries
$balancedEntries[] = false;
//verifies which of the options are active
$isWActive = (boolean)$this->_config[self::W];
$isXActive = (boolean)$this->_config[self::X];
$isYActive = (boolean)$this->_config[self::Y];
$isZActive = (boolean)$this->_config[self::Z];
//get configured percentage of each
$WPercentage = (int)$this->_config[self::LOAD_BALANCE_W];
$XPercentage = (int)$this->_config[self::LOAD_BALANCE_X];
$YPercentage = (int)$this->_config[self::LOAD_BALANCE_Y];
$ZPercentage = (int)$this->_config[self::LOAD_BALANCE_Z];
//here you fill the array according to the proportion defined by the percentages
if ($isWActive) {
for ($i = 0; $i < $WPercentage; $i++) {
$balancedEntries[] = self::W;
}
}
if ($isXActive) {
for ($i = 0; $i < $XPercentage; $i++) {
$balancedEntries[] = self::X;
}
}
if ($isYActive) {
for ($i = 0; $i < $YPercentage; $i++) {
$balancedEntries[] = self::Y;
}
}
if ($isZActive) {
for ($i = 0; $i < $ZPercentage; $i++) {
$balancedEntries[] = self::Z;
}
}
return $balancedEntries;
}
And then, in case you want a proportion of 1 to 100 (as in percentages):
$balancedResult = $balancedEntries[array_rand($balancedEntries, 1)];
Since array_rand will return 1 key from the original array, you use it to get it's value.
Another try, this should work for your case - But it only work if you have an adapter as a single char string, this is not visible by your question.
public function handleAdapter()
{
# a map with all adapters
$map = array(
self::W => self::LOAD_BALANCE_W,
self::X => self::LOAD_BALANCE_X,
self::Y => self::LOAD_BALANCE_Y,
self::Z => self::LOAD_BALANCE_Z
);
# generate a string map with one char per percentage point
$stringMap = "";
foreach($map as $key => $value){
# skip if disabled
if(!$this->_config[$key]) continue;
# repeat the key for each percentage point
$stringMap .= str_repeat($key, (int)$this->_config[$value]);
}
# return a random string char from the map
return $stringMap[rand(0, strlen($stringMap) - 1)];
}
Edit: I've misunderstood the question, the answer is wrong.
I understand your question so that you always want to return the adapter with the lowest load to force traffic to this adapter.
public function handleAdapter()
{
$isWActive = (boolean)$this->_config[self::W];
$isXActive = (boolean)$this->_config[self::X];
$isYActive = (boolean)$this->_config[self::Y];
$isZActive = (boolean)$this->_config[self::Z];
$WPercentage = (int)$this->_config[self::LOAD_BALANCE_W];
$XPercentage = (int)$this->_config[self::LOAD_BALANCE_X];
$YPercentage = (int)$this->_config[self::LOAD_BALANCE_Y];
$ZPercentage = (int)$this->_config[self::LOAD_BALANCE_Z];
$map = array();
if($isWActive) $map[self::W] = $WPercentage;
if($isXActive) $map[self::X] = $XPercentage;
if($isYActive) $map[self::Y] = $YPercentage;
if($isZActive) $map[self::Z] = $ZPercentage;
asort($map);
return key($map);
}
Edit: Fixed wrong sort(), you need asort() to maintain the index.

How do I delete course enrolments in moodle in bulk?

Moodle has a built in per course reset ability. I want to reset all my courses.
Sorry to bring this old post back but after a long struggle I finally got that code to work. I've tested it on a Moodle 1.9.7 enviroment
<?php
require('../config.php');
require_once('reset_form.php');
$courseids = array(8,9,11);
foreach ($courseids as &$value) {
$data->MAX_FILE_SIZE = 8097152;
$data->reset_start_date = 1251781200;
$data->reset_events = 1;
$data->reset_logs = 1;
$data->reset_notes = 1;
$data->reset_roles = Array(5);
$data->mform_showadvanced_last = 0;
$data->reset_roles_local = 1;
$data->reset_gradebook_grades = 1;
$data->reset_assignment_submissions = 1;
$data->reset_forum_all = 1;
$data->reset_quiz_attempts = 1;
$data->id = $value;
require_login($value);
require_capability('moodle/course:update', get_context_instance(CONTEXT_COURSE, $value));
$status = reset_course_userdata($data);
}
?>
Ok, I figued it out, but be very carful. If you do not know what you are doing do not use this code, you could do a lot of damage to your DB. This does the "default" course reset to all course ids in the array.
<?php
require('../config.php');
require_once('reset_form.php');
$courseids = array(8,9,11);
foreach ($courseids as &$value) {
$data->MAX_FILE_SIZE = 8097152;
$data->reset_start_date = 1251781200;
$data->reset_events = 1;
$data->reset_logs = 1;
$data->reset_notes = 1;
$data->reset_roles = Array(5);
$data->mform_showadvanced_last = 0;
$data->reset_roles_local = 1;
$data->reset_gradebook_grades = 1;
$data->reset_assignment_submissions = 1;
$data->reset_forum_all = 1;
$data->id = $value;
$status = reset_course_userdata($data);
}
?>
You should not reset courses this way, its too risky. Use the Course administration feature Choose the course, find the course admin. block, click the reset button, very simple. If you have only 3 courses, this takes about 30 seconds.

Categories