PHP output all possible number combinations - php

Ok, I've almost finished my script, but my output is not quite as supposed to be. Scripts task is to create all possible number combinations from the sum of all multidimensional array keys. Ive edited few scripts and combined in one script, but I cant seem to get desired output.
Ok, for example, lets say I have array like this one:
$test = array(0 => array(53, 22, 12),
1 => array(94, 84, 94),
2 => array(56, 45, 104)
);
Then I fetch array keys and store them in new array:
foreach ($test as $key => $row) {
$output[] = count($row);
}
for($keycount = 1; $keycount <= count($output); $keycount++){
$newarray[$keycount] = $keycount;
}
And then I count keys from newly created array, so the final combination is based on that number. In aforementioned example, I have 3 combinations, so the final array is supposed to look like this:
111
211
311
121
221
321
131
231
331
112
.
.
.
333
But with my script:
$arraycount = count($newarray);
$maxcombinations = pow($arraycount, $arraycount);
$return = array();
$conversion = array();
foreach ($newarray as $key => $value) {
$conversion[] = $key;
}
for ($i = 0; $i < $maxcombinations; $i++) {
$combination = base_convert($i, 10, $arraycount);
$combination = str_pad($combination, $arraycount, "0", STR_PAD_BOTH);
$return[$i][] = substr(strtr($combination, $conversion), 1, $arraycount);
}
echo "<pre>".print_r($return, true)."</pre>";
I'm getting output like this:
Array
(
[0] => Array
(
[0] => 111
)
[1] => Array
(
[0] => 121
)
[2] => Array
(
[0] => 131
)
[3] => Array
(
[0] => 211
)
[4] => Array
(
[0] => 221
)
[5] => Array
(
[0] => 231
)
[6] => Array
(
[0] => 311
)

You are using array like $return[$i][] thus you are getting your output as unexpected
Try
$return[$i] = substr(strtr($combination, $conversion), 1, $arraycount);
Instead of
$return[$i][] = substr(strtr($combination, $conversion), 1, $arraycount);

Related

How to check if an array index contains a value

I have an array with some values in different spots. I want to check if there is a value in the index then put it in a new array starting at 0 then put in index 1 then next value at index 2 and so on. I need to shorten it and move them all to the left really.
Array ( [0] => 53 [1] => [2] => 55 [3] => 76 [4] => [5] => [6] => [7] => )
The new array would be:
newArray ( [0] => 53 [1] =>55 [2] => 76)
Maybe something like this:
for ($i=0; $i < sizeof($questionWorth); $i++)
{
if($questionWorth[$i] has a value)
{
put it in new array starting at index zero
then increment the index of new array
}
}
To only get values that is not NULL or empty you could use array_filter() and array_values() like this:
$array = array(76, NULL, NULL, 56);
// remove empty values from array, notice that since no callback
// is supplied values that evaluates to false will be removed
$array = array_filter($array);
// since array_filter will preserve the array keys
// you can use array_values() to reindex the array numerically
$array = array_values($array);
// prints Array ( [0] => 76 [1] => 56 )
print_r($array);
You can use
array_filter($yourArray)
It will remove all empty values for you
Try array_filter which makes exactly this
var_dump(array_filter(array(0 => 55, 1 => 60, 2 => null)))
If you want to check if an index has a value, do this :
$variable = array ([0] => 53, [1] => , [2] => 55, [3] => 76, [4] => , [5] => , [6] => , [7] => )
foreach ($variable as $key => $value) {
var_dump($key.' => '.$value);
}
It's as simple as this: if ( $array [$i] ), and then put the value in another array with another counter that starts from 0.
$array = array(76, NULL, NULL, 56);
$count = 0;
for ($i=0; $i < sizeof($array); $i++)
{
if($array[$i])
{
$arr[$count] = $array[$i];
$count++;
}
};
print_r($array);
print_r($arr);

How to group keys and values of an (sub)array and sum its values using PHP? [duplicate]

This question already has answers here:
Group array data on one column and sum data from another column
(5 answers)
Closed 9 months ago.
I have the following array
Array (
[0] => Array
(
[0] => ALFA
[1] => 213
)
[1] => Array
(
[0] => ALFA
[1] => 151
)
[2] => Array
(
[0] => ALFA
[1] => 197
)
[3] => Array
(
[0] => BETA
[1] => 167
)
[4] => Array
(
[0] => ZETA
[1] => 254
)
[5] => Array
(
[0] => GAMA
[1] => 138
)
[6] => Array
(
[0] => GAMA
[1] => 213
)
)
And I would like to group the key[0] of the subarray so I can see how many equal keys it has.
Something like that:
ALFA => 3
BETA => 1
EPSI => 1
GAMA => 2
I tried with array_count_values, but without success.
foreach ($array as $value) {
echo '<pre>';
print_r(array_count_values($value));
echo '</pre>';
}
With that we have following result:
Array
(
[ALFA] => 1
[213] => 1
)
Array
(
[ALFA] => 1
[151] => 1
)
...
Array
(
[GAMA] => 1
[213] => 1
)
And after that I would like to sum the values of each group as well.
ALFA => 213 + 151 + 197
BETA => 167
ZETA => 254
GAMA => 138 + 213
I think that when we solve the first part of the problem, the second would follow easier with quite the same method.
The final purpose is to divide the sum of values by the number of occurrences of each key group, so we can have an average of the values just like that:
ALFA => (213+151+197) / 3 = 187
BETA => 167
ZETA => 254
GAMA => (138+213) / 2 = 175,5
This is not the main problem, but as I said, I'm stuck with the beginning of the solution and would appreciate any help.
I'm surprised at all the long and complicated answers. However, the initial foreach to model your data to something manageable is needed. After that you just need to do a really simple array_walk.
<?php
$result = array();
foreach ($array as $el) {
if (!array_key_exists($el[0], $result)) {
$result[$el[0]] = array();
}
$result[$el[0]][] = $el[1];
}
array_walk($result, create_function('&$v,$k', '$v = array_sum($v) / count($v);'));
?>
Result:
Array
(
[ALFA] => 187
[BETA] => 167
[ZETA] => 254
[GAMA] => 175.5
)
Solution for you is here:
Code:
$input = [
['alfa', 123],
['alfa', 223],
['alfa', 122],
['alfa', 554],
['alfa', 34],
['dalfa', 123],
['halfa', 223],
['dalfa', 122],
['halfa', 554],
['ralfa', 34]
];
$result = [];
foreach ($input as $node) {
if (isset($result[$node[0]])) {
$result[$node[0]] = ['sum' => $result[$node[0]]['sum'] + $node[1], 'count' => $result[$node[0]]['count'] + 1];
} else {
$result[$node[0]] = ['sum' => $node[1], 'count' => 1];
}
}
print_r($result);
foreach ($result as $key => &$data) {
$data = $data['sum'] / $data['count'];
}
print_r($result);
Output:
Array
(
[alfa] => Array
(
[sum] => 1056
[count] => 5
)
[dalfa] => Array
(
[sum] => 245
[count] => 2
)
[halfa] => Array
(
[sum] => 777
[count] => 2
)
[ralfa] => Array
(
[sum] => 34
[count] => 1
)
)
Array
(
[alfa] => 211.2
[dalfa] => 122.5
[halfa] => 388.5
[ralfa] => 34
)
$sort = array();
foreach ($array as $value) {
$sort[$value[0]][] = $value[1];
}
then you count how many keys each has
$keys = array();
foreach($sort as $k => $v) {
$keys[$k] = count($v);
}
then for calculating the amount
$sum = array();
$average = array();
foreach($sort as $k => $v) {
$amount = 0;
foreach($v as $val) {
$amount += $val;
}
$sum[$k] = $amount;
$average[$k] = $amount / $keys[$k];
}
HOWEVER, If you want all the details in one array:
$final = array();
foreach ($array as $value) {
$final[$value[0]]["values"][] = $value[1];
}
foreach($final as $k => $v) {
$final[$k]["amount"] = count($v['values']);
$amount = 0;
foreach($v['values'] as $val) {
$amount += $val;
}
$final[$k]["sum"] = $amount;
$final[$k]["average"] = $amount / $final[$k]["amount"];
}
example: http://jdl-enterprises.co.uk/sof/25789697.php
Includes Output
Just copy the codes to your favorite text editor, sure it works perfectly.
$items = [
['ALFA',213],
['ALFA',151],
['ALFA',197],
['BETA',167],
['ZETA',254],
['GAMA',138],
['GAMA',213]
];
echo '<pre>' . print_r($items,true) . '</pre>';
$result;
foreach ($items as $value) {
# code...
if (isset($result[$value[0]])) {
$sum = $result[$value[0]]['sum'] + $value[1];
$count = $result[$value[0]]['count'] + 1;
$result[$value[0]] = ['sum' => $sum , 'count' => $count, 'divided' => ($sum / $count)];
} else {
$result[$value[0]] = ['sum' => $value[1] , 'count' => 1 , 'divided' => ($value[1] / 1) ];
}
}
echo '<pre>' . print_r($result,true) . '</pre>';
$myArray = [
["ALFA",213],
["ALFA",151],
["ALFA",197],
["BETA",167],
["ZETA",254],
["GAMA",138],
["GAMA",213]
];
$a1 = array(); //TEMPORARY ARRAY FOR KEEPING COUNT & TOTAL VALUES
$res = array(); //ARRAY USED TO KEEP RESULT
foreach($myArray as $val)
{
//AVOID PESKY NOTICES FOR UNDEFINED INDEXES
if ( !array_key_exists($val[0],$a1) ) {
$a1[$val[0]] = array("count" => 0,"total" => 0);
$res[$val[0]] = 0;
}
//INCREMENT THE COUNT OF INSTANCES OF THIS KEY
$a1[$val[0]]["count"]++;
//INCREMENT THE TOTAL VALUE OF INSTANCES OF THIS KEY
$a1[$val[0]]["total"]+=$val[1];
// UPDATE RESULT ARRAY
$res[$val[0]] = $a1[$val[0]]["total"] / $a1[$val[0]]["count"];
}
print_r($res);
Should result in:
Array
(
[ALFA] => 187
[BETA] => 167
[ZETA] => 254
[GAMA] => 175.5
)
Sample: http://phpfiddle.org/lite/code/a7nt-5svf

Combine two multidimensioal arrays and set one as keys

I have these two arrays, which I need to combine
Array (
[0] => Column 1
[1] => Column 2
[2] => Column 3
)
Array (
[0] => Array (
[0] => 111
[1] => 222
[2] => 333
)
[1] => Array (
[0] => 444
[1] => 555
[2] => 666
)
)
into this
Array (
[0] => Array (
[Column 1] => 111
[Column 2] => 222
[Column 3] => 333
)
[1] => Array (
[Column 1] => 444
[Column 2] => 555
[Column 3] => 666
)
)
This is what I have and it works, but I am sure it can be done in a simpler way:
$values = array( array( 1,2,3), array( 4,5,6) );
$fields = array( 'Column 1','Column 2','Column 3');
$i = 0;
$j = 0;
$l = 0;
$rows = array();
$columns = array();
foreach($values as $val) {
$rows[] = $val;
foreach ($fields as &$field) {
$columns[$j][$i] = $field;
$i++;
}
$i = 0;
$j++;
}
foreach($columns as $c){
$result[] = array_combine($c,$rows[$l]);
$l++;
}
What I would like is to clean it up if possible. I do have my struggle with arrays sometimes and this one really messed with my head. :-)
Iterate over the array of arrays and pass each array to array_combine [docs], together with the keys:
$result = array();
foreach($values as $key => $value) {
$result[$key] = array_combine($fields, $value);
}
I think array_combine() like you did is a simple as you can get it. PHP doesn't have a function for everything, but you can make it into whatever your needs are at that moment, so it looks fine to me.
A bit odd you'd put the values and the keys into separate arrays before tho, you could simply do a foreach on the big one I think... or maybe I looked at the code too quickly?

PHP Array numbers

Easy question, I filled my array the following way:
$options = range(1, 10);
This will result:
array
(
[0] => 1
[1] => 2
etc. etc.
)
This is not the result I want..
I need my array like this:
array
(
[1] => 1
[2] => 2
etc.
)
How to accomplish this easy task?
Maybe like this:
$options = range(0, 10);
unset($options[0]);
working example
<?php
for( $i = 1; $i <= 10; $i ++ ) {
$array[$i] = $i;
}
Voila. :)
if you want a one-liner instead of a for-loop like Berry suggested, just use array_combine:
$array = array_combine(range(1,10),range(1,10));
function myRange($start, $limit, $step)
{
$myArr = array();
foreach((array) range($start, $limit,$step) as $k => $v)
{
$myArr[$k+1] = $v;
}
return $myArr;
}
print_r(myRange(0, 100, 10));
?>
Result
------
Array
(
[1] => 0
[2] => 10
[3] => 20
[4] => 30
[5] => 40
[6] => 50
[7] => 60
[8] => 70
[9] => 80
[10] => 90
[11] => 100
)
Or just shift the array
foreach ( $array as $key => $val )
$result[ $key+1 ] = $val;

Loop through array and remove duplicates

I have the following array for tire sizes:
Array
(
[0] => 155
[1] => 70
[2] => 13
)
Array
(
[0] => 155
[1] => 80
[2] => 13
)
Array
(
[0] => 165
[1] => 65
[2] => 14
)
Array
(
[0] => 175
[1] => 65
[2] => 14
)
Array
(
[0] => 175
[1] => 70
[2] => 13
)
Array
(
[0] => 175
[1] => 70
[2] => 14
)
and so on. Now I am creating a drop down so people can select the tire size they are searching for. so here is my PHP code:
include 'database.php';
$result = $mysqli->query('SELECT DISTINCT SKU_SIZE FROM SKU_DATA WHERE SKU_BRANDNAME = "'.$brand.'" ORDER BY SKU_SIZE');
while( $row = $result->fetch_assoc()){
$sku_size = $row['SKU_SIZE'];
$chars = preg_split('/[^\d]/', $sku_size, -1, PREG_SPLIT_NO_EMPTY);
echo "<option>".$chars[0]."</option>";
}
Now that code is just showing the first number in each array, for the very first drop down they select.
Right now it is showing 155, 155, 165, 175, 175 - and what I want it to do is just show the unique values so it would just show 155, 165, 175.
Update: Thanks! I got that part working. One quick question.. the order is not quite right, not sure what I am doing wrong. Here is a preview:
Create an array and check to see if each value is in the array before outputting it. If it is not in the array, add it in before outputting.
include 'database.php';
$result = $mysqli->query(
'SELECT DISTINCT SKU_SIZE
FROM SKU_DATA WHERE SKU_BRANDNAME = "'.$brand.'"
ORDER BY SKU_SIZE'
);
$seen = array();
while( $row = $result->fetch_assoc()){
$sku_size = $row['SKU_SIZE'];
$chars = preg_split('/[^\d]/', $sku_size, -1, PREG_SPLIT_NO_EMPTY);
if(in_array($chars[0], $seen))
continue;
$seen[] = $chars[0];
echo "<option>".$chars[0]."</option>";
}
You can remove any duplicate unique items from an array using the array_unique() function.
EG:
$arrays = array(1,2,3) + array(1,2,3);
print_r(array_unique($arrays));
// Will print just: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 )
use this:
while( $row = $result->fetch_assoc()){
$sku_size = $row['SKU_SIZE'];
$chars = preg_split('/[^\d]/', $sku_size, -1, PREG_SPLIT_NO_EMPTY);
$sizes[$chars[0]] = true;
}
ksort($sizes, SORT_NUMERIC);
foreach ($sizes as $size => $tmp){
echo "<option value=\"$size\">$size</option>";
}
Use a temporary array to store the numbers that have been echoed then.
Make a new array with just the first value
$diameter = array();
foreach ($tires as $tire) {
$diameter[] = $tire[0];
}
Then, use array_unique() to remove the duplicates, or only add them to $diameter if they are not already in there.
Then use that $diameter array to create the dropdown.
This has the advantage that you can also sort the $diameter array.

Categories