I'm facing a technical problem here, I have an array [PER_DAY, PER_SIZE, PER_TYPE], I want to find combination all of the item without repeating the element, the result should be
[PER_DAY]
[PER_SIZE]
[PER_TYPE]
[PER_DAY, PER_SIZE]
[PER_DAY, PER_TYPE]
[PER_SIZE, PER_TYPE]
[PER_DAY, PER_SIZE, PER_TYPE]
This code repeating same value, so the result is too much.
$arr = ['PER_DAY', 'PER_SIZE', 'PER_TYPE'];
$result = [];
function combinations($arr, $level, &$result, $curr=[]) {
for($i = 0; $i < count($arr); $i++) {
$new = array_merge($curr, array($arr[$i]));
if($level == 1) {
sort($new);
if (!in_array($new, $result)) {
$result[] = $new;
}
} else {
combinations($arr, $level - 1, $result, $new);
}
}
}
for ($i = 0; $i<count($arr); $i++) {
combinations($arr, $i+1, $result);
}
This question possible duplicate, but I cannot found example similar like this, thanks.
function pc_array_power_set($array) {
// initialize by adding the empty set
$results = array(array( ));
foreach ($array as $element)
foreach ($results as $combination)
array_push($results, array_merge(array($element), $combination));
return array_filter($results);
}
$set = ['PER_DAY', 'PER_SIZE', 'PER_TYPE'];
$power_set = pc_array_power_set($set);
echo '<pre>';
print_r($power_set);
You have make combination from array, will help you :-PHP array combinations
Related
This question already has answers here:
Code after a return statement in a PHP function
(3 answers)
Closed 6 months ago.
please check my code. i have some program to return the third largest word in a given array.
if in the third largest word has a same letters long, so retrun the last one.
for example ['world', 'hello', 'before', 'all', 'dr'] the output should be 'hello'.
my program is working fine, however when I want to echo the $result, the code doesn't execute.
here is my code:
<?php
$array = ['world', 'hello', 'before', 'all', 'dr'];
$array2 = [];
foreach ($array as $value) {
$array2[$value] = strlen($value);
}
asort($array2);
$slice = array_slice($array2, -3);
$array3 = [];
foreach ($slice as $key => $value) {
$array3[] = $key;
}
$result = "THIS RESULT SHOULD BE RE ASSIGNED, BUT WHY !!!!!";
for ($i = count($array3) - 1; $i >= 0; $i--) {
if ($i == 0) {
$result = $array3[$i];
return $result;
}
if (strlen($array3[$i]) == strlen($array3[$i - 1])) {
$result = $array3[$i];
return $result;
}
}
echo "THIS LINE IS NOT WORKING";
echo $result;
You have to use break instead of return.
<?php
$array = ['world', 'hello', 'before', 'all', 'dr'];
$array2 = [];
foreach ($array as $value) {
$array2[$value] = strlen($value);
}
asort($array2);
$slice = array_slice($array2, -3);
$array3 = [];
foreach ($slice as $key => $value) {
$array3[] = $key;
}
$result = "";
for ($i = count($array3) - 1; $i >= 0; $i--) {
if ($i == 0) {
$result = $array3[$i];
break;
}
if (strlen($array3[$i]) == strlen($array3[$i - 1])) {
$result = $array3[$i];
break;
}
}
echo $result;
Simply remove the return statements in the loop. instead of return, perhaps use break.
You can try this way as well.
<?php
/**
* Read more about here
* https://www.php.net/manual/en/function.usort.php
*/
function sort_by_length($a,$b){
return strlen($b)-strlen($a);
}
$array =['world', 'hello', 'before', 'all', 'dr'];
usort($array,'sort_by_length'); // sorting array with a custom function.
if(count($array) >= 2) {
$sliced = array_slice($array, 2);
$result = $sliced[0];
/**
* Read more at
* 1. https://www.php.net/manual/en/function.next.php
* 2. https://www.php.net/manual/en/function.current.php
*/
while(strlen(current($sliced)) == strlen(next($sliced))){
$result = current($sliced);
}
echo $result;
} else {
echo "Not enough items in array.";
}
This will output
hello
Remove the return .It return the value so any code after it will not be executed.
I want to combine two arrays into a dictionary.
The keys will be the distinct values of the first array, the values will be all values from the second array, at matching index positions of the key.
<?php
$a=[2,3,4,5,6,7,8,9,10];
$b=[1,1,3,2,1,2,6,8,8];
?>
array_combine($b,$a);
Expected result as
<?php
/*
Value '1' occurs at index 0, 1 and 4 in $b
Those indices map to values 2, 3 and 6 in $a
*/
$result=[1=>[2,3,6],3=>4,2=>[5,7],6=>8,8=>[9,10]];
?>
There are quite a few PHP array functions. I'm not aware of one that solves your specific problem. you might be able to use some combination of built in php array functions but it might take you a while to weed through your choices and put them together in the correct way. I would just write my own function.
Something like this:
function myCustomArrayFormatter($array1, $array2) {
$result = array();
$num_occurrences = array_count_values($array1);
foreach ($array1 AS $key => $var) {
if ($num_occurrences[$var] > 1) {
$result[$var][] = $array2[$key];
} else {
$result[$var] = $array2[$key];
}
}
return $result;
}
hope that helps.
$a=[2,3,4,5,6,7,8,9,10];
$b=[1,1,3,2,1,2,6,8,8];
$results = array();
for ($x = 0; $x < count($b); $x++) {
$index = $b[$x];
if(array_key_exists ($index, $results)){
$temp = $results[$index];
}else{
$temp = array();
}
$temp[] = $a[$x];
$results[$index] = $temp;
}
print_r($results);
Here's one way to do this:
$res = [];
foreach ($b as $b_index => $b_val) {
if (!empty($res[$b_val])) {
if (is_array($res[$b_val])) {
$res[$b_val][] = $a[$b_index];
} else {
$res[$b_val] = [$res[$b_val], $a[$b_index]];
}
} else {
$res[$b_val] = $a[$b_index];
}
}
var_dump($res);
UPDATE: another way to do this:
$val_to_index = array_combine($a, $b);
$result = [];
foreach ($val_to_index as $value => $index) {
if(empty($result[$index])){
$result[$index] = $value;
} else if(is_array($result[$index])){
$result[$index][] = $value;
} else {
$result[$index] = [$result[$index], $value];
}
}
var_dump($result);
I have an issue to deal with here (a logical error in my code 99%). I just can't seem to find the way to fix it, but I bet one of you will find the problem in no time!
I have to create a function which sorts array passed to it in asc or desc order, but can't use any array sorting functions !
I've been struggling with loops until now and I finally want to ask help from other devs ( you ).
Currently only code for ascending is worked on, descending will be no problem I assume once I do this one. It kinda of does sort values up to some point, but then stops ( it stops if the next smallest value is at the end of the passed array ). What could I do to prevent this and make it sort the whole array and it's elements?
Here is the code so far.
<?php
function order_array($array,$mode = 'ascending') {
$length = count($array);
if($mode == 'descending') {
return $array;
} else {
$sorted_array = array();
$used_indexes = array();
for($i = 0; $i < $length; $i++) {
$smallest = true;
echo $array[$i] . '<br/>';
for($y = 0; $y < $length; $y++) {
//echo $array[$i] . ' > ' . $array[$y] . '<br/>';
// if at ANY time during checking element vs other ones in his array, he is BIGGER than that element
// set smallest to false
if(!in_array($y,$used_indexes)) {
if($array[$i] > $array[$y]) {
$smallest = false;
break;
}
}
}
if($smallest) {
$sorted_array[] = $array[$i];
$used_indexes[] = $i;
}
}
return $sorted_array;
}
}
$array_to_sort = array(1, 3, 100, 99, 33, 20);
$sorted_array = order_array($array_to_sort);
print_r($sorted_array);
?>
I've solved the issue myself by doing it completely different. Now it sorts correctly all the elements of the passed in array. The logical issue I had was of using for() loop. The for() loop ran only a set ( length of passed array ) number of times, while we need it to loop more than that, because we will need to loop all the way untill we have a new sorted array in ascending order. Here is the code that will work
function order_array($array,$mode = 'ascending') {
if($mode == 'descending') {
// for() wont work here, since it will only loop an array length of times, when we would need it
// to loop more than that.
while(count($array)){
$value = MAX($array);
$key = array_search($value, $array);
if ($key !== false) {
unset($array[$key]);
}
$sorted[] = $value;
}
return $sorted;
} else {
// for() wont work here, since it will only loop an array length of times, when we would need it
// to loop more than that.
while(count($array)){
$value = MIN($array);
$key = array_search($value, $array);
if ($key !== false) {
unset($array[$key]);
}
$sorted[] = $value;
}
return $sorted;
}
}
function order_array($array,$mode = 'ascending') {
$length = count($array);
$sorted_array = array();
$used_indexes = array();
for($i = 0; $i < $length; $i++) {
$smallest = true;
echo $array[$i] . '<br/>';
for($y = 0; $y < $length; $y++) {
//echo $array[$i] . ' > ' . $array[$y] . '<br/>';
// if at ANY time during checking element vs other ones in his array, he is BIGGER than that element
// set smallest to false
if(!in_array($y,$used_indexes)) {
if($array[$i] > $array[$y]) {
$smallest = false;
break;
}
}
}
if($smallest) {
$sorted_array[] = $array[$i];
$used_indexes[] = $i;
}
if($mode == 'descending') {
return array_reverse($sorted_array);
}
return $sorted_array;
}
}
I have the following code:
$chart_data = array();
foreach ($range as $range_day) {
foreach ($numbers as $number) {
if($range_day == $number['date']){
#$chart_data[$range_day] += $number['events'];
} else {
if(isset($chart_data[$range_day])){
$chart_data[$range_day] += 0;
}
}
}
}
This line: $chart_data[$range_day] += 0; was giving me an undefined index error, so I added the isset check, but it's not set so it wrecks my array. I know that it's not set, and I don't care, but I read all over that the # solution is in poor taste. How can I remove the error the correct way?
You could just set it to zero at the beginning:
$chart_data = array();
foreach ($range as $range_day) {
$chart_data[$range_day] = 0;
foreach ($numbers as $number) {
if($range_day == $number['date']){
$chart_data[$range_day] += $number['events'];
} else {
if(isset($chart_data[$range_day])){
$chart_data[$range_day] += 0;
}
}
}
}
Did you take a look at the array_key_exists function: http://php.net/manual/en/function.array-key-exists.php ?
Something like:
$chart_data = array();
foreach ($range as $range_day) {
foreach ($numbers as $number) {
if(!array_key_exists($range_day, $array)) {
$chart_data[$range_day] = 0;
}
if($range_day == $number['date']){
$chart_data[$range_day] += $number['events'];
}
}
}
You can check if it's not set, then set it:
foreach ($numbers as $number) {
if (!isset($chart_data[$range_day])) {
$chart_data[$range_day] = 0;
}
if ($range_day == $number['date']) {
$chart_data[$range_day] += $number['events'];
} else {
$chart_data[$range_day] += 0; // you're just adding 0 so why have this line at all?
}
}
This answers assumes that there is the possibility that $range could contain a duplicate $range_day and so it won't overwrite the corresponding element in $chart_data.
Hi anybody can help me to find the maximum value of the array that are given in the below . i expect the result of 650 is the maximum value....
$my_array = array(array(128,300,140)10,15,array(130,array(500,650)));
Here you go, using RecursiveArrayIterator in 3 readable lines of code:
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
$flattenedArray = iterator_to_array($it);
$max = max($flattenedArray);
Or, if you want to not flatten (and copy), but prefer to iterate (uses far less memory, but slower):
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
$max = 0;
foreach ($it as $value) {
$max = max($value, $max);
}
Flatten the array, then call max() on it. The return value of max() should be 650 from your example.
Also possible is
$data = array(array(128,300,140),10,15,array(130,array(500,650)));
$max = 0;
array_walk_recursive(
$data,
function($val) use (&$max) {
if($val > $max) $max = $val;
}
);
echo $max; // 650
You could also do it recursively, if the item is an array, call the function again to return the max item from that array.
In the end you should have always the max item and then in the last iteration, you could call the max from those results.
This does the trick:
function flatten($ar) {
$toflat = array($ar);
$res = array();
while (($r = array_shift($toflat)) !== NULL) {
foreach ($r as $v) {
if (is_array($v)) {
$toflat[] = $v;
} else {
$res[] = $v;
}
}
}
return $res;
}
$arr = array(array(128,300,140),10,15,array(130,array(500,650)));
echo max(array_flatten($arr));
EDIT: Updated flatten array with the one at How to "flatten" a multi-dimensional array to simple one in PHP?
<?php
$my_array = array(array(128,300,140),10,15,array(130,array(500,650)));
function findLargest($arr) {
$largest = 0;
foreach ($arr as $item) {
if (is_array($item)) {
$item = findLargest($item);
}
if ($item > $largest) {
$largest = $item;
}
}
return $largest;
}
echo "Largest is ".findLargest($my_array)."\n";
?>
function maximum($in)
{
if (!is_array($in)) $max = $in;
else foreach ($in as $element)
{
$elementMax = maximum($element);
if (isset($max)) $max = max($elementMax, $max); else $max = $elementMax;
}
return $max;
}