Finding the subsets of an array in PHP
You wish for the power set of $attributes
? That is what your question implies.
An example can be found here (quoted for completeness)
<?php
/**
* Returns the power set of a one dimensional array, a 2-D array.
* [a,b,c] -> [ [a], [b], [c], [a, b], [a, c], [b, c], [a, b, c] ]
*/
function powerSet($in,$minLength = 1) {
$count = count($in);
$members = pow(2,$count);
$return = array();
for ($i = 0; $i < $members; $i++) {
$b = sprintf("%0".$count."b",$i);
$out = array();
for ($j = 0; $j < $count; $j++) {
if ($b{$j} == '1') $out[] = $in[$j];
}
if (count($out) >= $minLength) {
$return[] = $out;
}
}
return $return;
}
Get subset of array based on values in PHP
You can use array_filter
to filter an array down to only the elements you're looking for. Set $subset
to whatever value you're searching for, and it'll return the matching elements, without changing the keys.
$subset = 2;
$results = array_filter($array, function ($item) use ($subset) {
return $item === $subset;
});
print_r($results);
Array
(
[3] => 2
[4] => 2
)
See https://eval.in/926983
how to find possible subsets of a given array?
The table is entirely unnecessary.
One idea is to imagine a bit wise representation of each weekday, whereby:
Monday = 1
Tuesday = 2
Wednesday = 4
Thursday = 8
Etc
Every combination of days can then be represented by a single number from 1 to 127.
See Working with bitcode for a fuller explanation
How to find sum of each subset in php?
The $result
in the function is array of arrays so you cannot just use array_sum
on it. In order to sum each of the sub-set you need to use array_map
together with array_sum
.
You can do it in the end of the function - just add print_r(array_map("array_sum", $results));
as last line (if you want it as output).
I liked @splash58 comment about using it outside the function with:
$ans = array_map("array_sum", powerSet($array));
Get a subset of an array based on an array of keys
array_diff_key
and array_intersect_key
are probably what you want.
Create subset of array in php
See array_chunk function.
To example:
$input_array = array('a', 'b', 'c', 'd', 'e');
print_r(array_chunk($input_array, 2));
Result:
Array
(
[0] => Array
(
[0] => a
[1] => b
)
[1] => Array
(
[0] => c
[1] => d
)
[2] => Array
(
[0] => e
)
)
Find all possible unique combinations of elements of an array in PHP
Fast solution using recursion, probably not the best way to do it, but it gets the job done.
<?php
$arr = array(1,2,3);
$result = array();
function combinations($arr, $level, &$result, $curr=array()) {
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);
}
// TEST
foreach ($result as $arr) {
echo join(" ", $arr) . '<br>';
}
?>
Find qualifying subsets and return value that immediately follows
I reckon it is simpler to read your data as a string instead of iterating elements in their current array form.
Just use a lookbehind pattern and match the next occurring integer.
Code: (Demo) (technically better accuracy)
$haystack = [0,0,0,1,1,0,1,1,0,0,1,1,0,0,1];
$needle = [1,1,0];
$regex = sprintf(
'/(?<=%s,)\d+/',
implode(',', $needle)
);
var_export(
preg_match_all($regex, implode(',', $haystack), $m)
? $m[0]
: []
);
Output:
array (
0 => '1',
1 => '0',
2 => '0',
)
Or an approach that processes the data in array form, can make iterated calls of array_slice()
to achieve the same result. (Demo)
$needleCount = count($needle);
$result = [];
foreach ($haystack as $i => $straw) {
$start = $i - $needleCount;
if (
$start >= 0
&& $needle === array_slice($haystack, $start, $needleCount)
) {
$result[] = $straw;
}
}
Related Topics
Error Message Strict Standards: Non-Static Method Should Not Be Called Statically in PHP
PHP: How to Remove Specific Element from an Array
PHP: Merge 2 Multidimensional Arrays
Including a Remote File in PHP
How to Write a File in Utf-8 Format
PHP: Warning: Sort() Expects Parameter 1 to Be Array, Resource Given
How to Install a Specific Version of Package Using Composer
How Can Strip Whitespaces in PHP'S Variable
PHP Get All Subdirectories of a Given Directory
PHP Error: Cannot Modify Header Information - Headers Already Sent
How to Check File Types of Uploaded Files in PHP
Difference in Accessing Arrays in PHP 5.3 and 5.4 or Some Configuration Mismatch
How to Upload & Save Files With Desired Name