Better way of looking for matching value to output result? - php

I have a few names I need to check for depending on the number associated with them. Right now I can accomplish this task with the following.
$detectInspector = array();
$detectInspector[558]="Name";
$detectInspector[559]="OtherName";
$detectInspector[560]="Someone";
echo $detectInspector[558];
The issue is I have hundreds of these I would have to type out. Is there an easier method to perhaps do something like
476 through 490 = name
518 through 530 = name
558 through 569 = othername
598 though 609 = othername
650 through 655 = someoneelse
690 through 695 = someoneelse
To explain how the code works:
Pull number from db
Check number against list to see who name
matches
echo result

You could try something like this :
First store your names within a multidimensional array with a name entry and an array with the ranges of the name. Obviously, the name is going to be set if the number is between the min and max value of each range.
$ranges = [
[
'name' => 'Jhon',
'ranges' => [
[1,50],
[120,200],
[401,409]
]
],
[
'name' => 'Jack',
'ranges' => [
[20,25],
[210,230],
],
],
[
'name' => 'Bill',
'ranges' => [
[245,270],
[301,350],
],
],
[
'name' => 'Steve',
'ranges' => [
[271,275],
],
],
];
$names = [];
foreach ($ranges as $nameProps) {
foreach ($nameProps['ranges'] as $range) {
list($min, $max) = $range;
$names[] = [
'name' => $nameProps['name'],
'min' => $min,
'max' => $max,
];
}
}
Then, assuming you get the $nb variable from the db :
$nb = 999;
$detectInspector = [];
for ($i = 1; $i <= $nb; $i++) {
$name = '';
foreach ($names as $k => $nameProps) {
if ($i >= $nameProps['min'] && $i <= $nameProps['max']) {
$name .= ($name ? ' | ' : '') . $nameProps['name'];
}
}
if ($name != '') {
$detectInspector[$i] = $name;
}
}
You can now use your $detectInspector value
var_dump($detectInspector);

Related

php get most and least occurring values from Multidimensional arrays

I want to get most and least occuring values from php sequential/indexes, assoc and multidimensional arrays
Consider the following dataSet
$dataSet = [
'users' =>
[
'id' => 1,
'name' => "Alex",
'username' => 'alex',
],
[
'id' => 2,
'name' => "Alex",
'username' => 'alex'
],
[
'id' => 2,
'name' => "Peter Khot",
'username' => 'peter',
]
];
Here above are samples dataSet
Here is what that i tried
function most_occurring(array $array, $key)
{
$dataSet = [];
$i = 0;
$keys = [];
foreach ($array as $k) {
if (in_array($k[$key], $keys)) {
$keys[$i] = $k[$key];
$dataSet[$i] = $k;
}
$i++;
}
return $dataSet;
}
I tried above code for most occurring values but not working at all, help me in most and least occuring values from arrays.
Thanks
Thanks to KIKO Software, you can still use array_count_values() for this cases. You will also need to use array_columns() and array_search() in this situation. You can refer to this link to see how array_search() helps in finding the maximum/minimum value and its corresponding key inside an array. To find the most or least occurrence, simply echo the last 6 variables that I have declared in the last 6 lines.
EDIT* reference:
unset
array_push
*And also, your first data in the assoc array is indexed 'user', but the second data in the assoc array is not indexed and hence it is indexed as 0.
$dataSet = [
'users' =>
[
'id' => 1,
'name' => "Alex",
'username' => 'alex',
],
[
'id' => 2,
'name' => "Alex",
'username' => 'alex'
],
[
'id' => 2,
'name' => "Peter Khot",
'username' => 'peter',
]
];
$id = array_column($dataSet,'id');
$name = array_column($dataSet, 'name');
$username = array_column($dataSet, 'username');
$occur_id = array_count_values($id);
$occur_name = array_count_values($name);
$occur_username = array_count_values($username);
$most_occur_id = array_search(max($occur_id),$occur_id);
$most_occur_name = array_search(max($occur_name),$occur_name);
$most_occur_username = array_search(max($occur_username),$occur_username);
$least_occur_id = array_search(min($occur_id),$occur_id);
$least_occur_name = array_search(min($occur_name),$occur_name);
$least_occur_username = array_search(min($occur_username),$occur_username);
EDIT*: (In case of multiple highest occurence OR all same occurence, just add below code right below the above code.)
$flag = true;
$most_occur_name_list = [];
$count = 0;
while($flag)
{
$most_occur_name_ct = max($occur_name);
if($most_occur_name_ct == $count || $count == 0)
{
array_push($most_occur_name_list,array_search($most_occur_name_ct,$occur_name));
unset($occur_name[array_search($most_occur_name_ct,$occur_name)]);
$count = $most_occur_name_ct;
if(count($occur_name) == 0)
{
$flag = false;
break;
}
}
else
{
$most_occur_name_ct = $count;
$flag = false;
break;
}
}
//must reinitialize the array
$occur_name = array_count_values($name);
$flag = true;
$least_occur_name_list = [];
$count = 0;
while($flag)
{
$least_occur_name_ct = min($occur_name);
if($least_occur_name_ct == $count || $count == 0)
{
array_push($least_occur_name_list,array_search($least_occur_name_ct,$occur_name));
unset($occur_name[array_search($least_occur_name_ct,$occur_name)]);
$count = $least_occur_name_ct;
if(count($occur_name) == 0)
{
$flag = false;
break;
}
}
else
{
$least_occur_name_ct = $count;
$flag = false;
break;
}
}
if($most_occur_name_ct == $least_occur_name_ct)
{
$most_occur_name_list = [];
$least_occur_name_list = [];
}
echo "<pre>";
print_r($most_occur_name_list);
If you wanted to get a list of the min and max number of occurrences for just 1 element of the multidimensional array, then this code may offer a shorter method - comments in code...
$dataSet = [
'users' =>
[
'id' => 1,
'name' => "Alex",
'username' => 'alex',
],
[
'id' => 2,
'name' => "Alex",
'username' => 'alex'
],
[
'id' => 2,
'name' => "Peter Khot",
'username' => 'peter',
],
[
'id' => 2,
'name' => "Peter Khot",
'username' => 'peter',
],
[
'id' => 2,
'name' => "Paul Khot",
'username' => 'Paul',
]
];
// Create an array which has the username column, but retaining the keys from
// the original array
$set = array_combine(array_keys($dataSet),
array_column($dataSet, "username" ));
// Summarise the values
$count = array_count_values($set);
// Get a list of the keys which match the max and min values
$minRecords = array_keys($count,min($count));
$maxRecords = array_keys($count,max($count));
// Fetch the details for the maximum value (first one returned)
$maxElements = [];
foreach ( $maxRecords as $max ) {
$maxElements[] = $dataSet[array_search($max, $set )];
}
// Same for min values
$minElements = [];
foreach ( $minRecords as $min ) {
$minElements[] = $dataSet[array_search($min, $set )];
}
print_r($maxElements);
print_r($minElements);
With the test data I've added, you get the output...
Array
(
[0] => Array
(
[id] => 1
[name] => Alex
[username] => alex
)
[1] => Array
(
[id] => 2
[name] => Peter Khot
[username] => peter
)
)
Array
(
[0] => Array
(
[id] => 2
[name] => Paul Khot
[username] => Paul
)
)

PHP grouping content of multidimensional array with new structure

I usually use Eloquent so transposing the data is much easier. However i'm struggling to this in vanilla PHP.
I have tried array_map(null, ...$array) however get an error due to it not being an array.
I have got the following keyed array:
[
'email' => [
"william.pool#gmail.com",
"martynleeball#gmail.com"
],
'lastName' => [
'Pool',
'Ball'
],
'firstName' => [
'William',
'Martyn'
],
'id' => [
'j8zwyk',
'1'
]
]
I need to convert this to the following format:
[
0 => [
'email' => "william.pool#gmail.com",
'lastName' => 'Pool',
'firstName' => 'William',
'id' => 'j8zwyk'
],
1 => [
'email' => "martynleeball#gmail.com",
'lastName' => 'Ball',
'firstName' => 'Martyn',
'id' => '1'
]
]
Create new array with length 2 and loop through origin array. In loop insert relevant item into new array.
So if your array has only 2 item per key use
$newArr = [];
foreach($arr as $key=>$item){
$newArr[0][$key] = $item[0];
$newArr[1][$key] = $item[1];
}
But if it has unknown item use
$newArr = [];
foreach($arr as $key=>$item){
foreach($item as $key2=>$item2)
$newArr[$key2][$key] = $item2;
}
Check result in demo
$newArray = [];
foreach ($array as $key => $value) {
for ($i = 0; $i < count($value); $i++) {
$newArray[$i][$key] = $value[$i];
}
}

Random weighted distribution

For example I have an array like:
$items = [
'0' => [
'name' => 'item1',
'percent' => 10
],
'2' => [
'name' => 'item2',
'percent' => 20
],
'3' => [
'name' => 'item3',
'percent' => 30
],
'4' => [
'name' => 'item4',
'percent' => 40
],
];
And function:
function echoRandomItem(){
}
If I call this function it should return 'name' of the item depending on the 'percent' value. Basically if I call this function 100 times it should return item1 10 times, item2 20 times, item3 30 times, item4 40 times.
Here is a solution I've come up with thanks to Oliver's hint. $items is a given array. wrand() function is responsible for random weighted distribution calculation.
$items = [
'1' => [
'name' => 'item1',
'rand' => 10
],
'2' => [
'name' => 'item2',
'rand' => 20
],
'3' => [
'name' => 'item3',
'rand' => 30
],
'4' => [
'name' => 'item4',
'rand' => 40
],
];
function wrand($data) {
foreach ($data as $value) {
$itemsRand[] = $value ['rand'];
}
$totalw = array_sum($itemsRand);
$rand = rand(1, $totalw);
$curw = 0;
foreach ($data as $val) {
$curw += $val['rand'];
if ($curw >= $rand) return $val['name'];
}
return end($data);
}
Further code simply calls wrand() function 100 times and counts the results.
static $item1 = 0;
static $item2 = 0;
static $item3 = 0;
static $item4 = 0;
for ($i = 0; $i < 100; $i++){
$k = wrand($items);
if ($k == 'item1') {
$item1++;
} elseif ($k == 'item2'){
$item2++;
} elseif ($k == 'item3'){
$item3++;
} elseif ($k == 'item4'){
$item4++;
}
}
echo "item1 = $item1<br>";
echo "item2 = $item2<br>";
echo "item3 = $item3<br>";
echo "item4 = $item4";

Php rearrange array according to the key

I tried convert the array type from $data to $data2 but didn't have success.
In the $data array all values placed according to dates.
But in the $data2 values are placed according to the title.
I wonder if it's convertable array.
$data['Group1']['Date1']['Empty'] = 5;
$data['Group1']['Date1']['Reservated'] = 1;
$data['Group1']['Date1']['WillReturn'] = 3;
$data['Group1']['Date1']['Remains'] = 1;
$data['Group1']['Date2']['Empty'] = 2;
$data['Group1']['Date2']['Reservated'] = 2;
$data['Group1']['Date2']['WillReturn'] = 3;
$data['Group1']['Date2']['Remains'] = -3;
$data['Group2']['Date1']['Empty'] = 0;
$data['Group2']['Date1']['Reservated'] = 1;
$data['Group2']['Date1']['WillReturn'] = 3;
$data['Group2']['Date1']['Remains'] = -4;
$data['Group2']['Date2']['Empty'] = 10;
$data['Group2']['Date2']['Reservated'] = 1;
$data['Group2']['Date2']['WillReturn'] = 1;
$data['Group2']['Date2']['Remains'] = 8;
$data2 = [
'Group1' => [
[ 'Title' => 'Empty',
'Date1' => 5,
'Date2' => 2,
],
[ 'Title' => 'Reservated',
'Date1' => 1,
'Date2' => 2,
],
[ 'Title' => 'WillReturn',
'Date1' => 3,
'Date2' => 3,
],
[ 'Title' => 'Remains',
'Date1' => 1,
'Date2' => -3,
],
// etc...
],
'Group2' => [
[ 'Title' => 'Empty',
'Date1' => 0,
'Date2' => 10,
],
[ 'Title' => 'Reservated',
'Date1' => 1,
'Date2' => 1,
],
[ 'Title' => 'WillReturn',
'Date1' => 3,
'Date2' => 1,
],
[ 'Title' => 'Remains',
'Date1' => -4,
'Date2' => -8,
],
// etc...
],
// etc...
];
Some try here:
$new = [];
$grp = array_keys($datax);
$i =0;
foreach($datax as $key => $val)
{
$dates = array_keys($val);
foreach($val as $k=>$v)
{
$cases = array_keys($v);
$caseAndVals[$i]=$v;
$i++;
}
}
$z =0;
$y = 0;
foreach($grp as $g)
{
foreach($cases as $c)
{
$new[$g][$z]['Title']=$c;
foreach($dates as $d)
{
$new[$g][$z][$d] = 'values which correspond to the date and title';
}
$z++;
}
}
I converted array according to group and cases but i didn't have success to place values corresponded dates...
You're very close.
To get the values which correspond to the date and title, use $data[$g][$d][$c].
And you need to reset $z to 0 each time through the $grp loop, so you get correct indexes on each group array.
$new = array();
$grp = array_keys($data);
foreach($data as $key => $val)
{
$dates = array_keys($val);
foreach($val as $k=>$v)
{
$cases = array_keys($v);
$caseAndVals[]=$v;
}
}
foreach($grp as $g)
{
$z = 0;
foreach($cases as $c)
{
$new[$g][$z]['Title']=$c;
foreach($dates as $d)
{
$new[$g][$z][$d] = $data[$g][$d][$c];
}
$z++;
}
}

PHP - How to create such array?

The question is simple, I want to create the array below dynamically, but the code I got now only outputs the last row. Is there anybody who knows what is wrong with my dynamically array creation?
$workingArray = [];
$workingArray =
[
0 =>
[
'id' => 1,
'name' => 'Name1',
],
1 =>
[
'id' => 2,
'name' => 'Name2',
]
];
echo json_encode($workingArray);
/* My not working array */
$i = 0;
$code = $_POST['code'];
$dynamicArray = [];
foreach ($Optionsclass->get_options() as $key => $value)
{
if ($value['id'] == $code)
{
$dynamicArray =
[
$i =>
[
'id' => $key,
'name' => $value['options']
]
];
$i++;
}
}
echo json_encode($dynamicArray);
You dont need to have the $i stuff that is adding another level to your array that you dont want.
$code = $_POST['code'];
$dynamicArray = [];
foreach ($Optionsclass->get_options() as $key => $value)
{
if ($value['id'] == $code)
{
$dynamicArray[] = ['id' => $key, 'name' => $value['options'];
}
}
echo json_encode($dynamicArray);
You are creating a new dynamic array at each iteration:
$dynamicArray =
[
$i =>
[
'id' => $key,
'name' => $value['options']
]
];
Instead, declare $dynamicArray = []; above the foreach, and then use:
array_push($dynamicArray, [ 'id' => $key, 'name' => $value['options']);
inside the array.

Categories