I am making a program that will output an array in ascending order BUT if there found matching number it will skip that and consider that later.
for example:
array = 2, 1, 3, 1, 5, 2;
output should be:
array = 1, 2, 3, 5, 1, 2 //first four sequence number(1,2,3,5) and then repeating number sequenced later.
Here is my code
<?php
if(isset($_POST['submit'])) {
$var = $_POST['in'];
$arr = explode(" ",$var);
sort($arr);
$size = sizeof($arr);
$arr2 = array();
$cnt=0;
$k=0;
for($i=0;$i<$size;$i++)
{
for($j=0;$j<$size;$j++) {
$k = $j + 1;
if($arr[$j] < $arr[$k]) {
$arr2[$j] = $arr[$j];
array_splice($arr,$j,1);
}
if($arr[$j] == $arr[$k]) {
continue;
$cnt++;
}
if($cnt==0) {
break;
}
}
}
foreach($arr2 as $value) {
echo " ".$value;
}
}
?>
<html>
<head></head>
<body>
<form method="post">
<h2>Enter data</h2>
<input type="text" name="in" placeholder="Enter data with spaces.."/>
<input type="submit" value="ok" name="submit"/>
</form>
</body>
</html>
It is not working. please correct the code.
Thanks
Please Try this:
$myArr = [] //with values 2, 1, 3, 1, 5, 2;
$tmp = $tmp2 = [];
foreach($myArr as $val){
if(!in_array($val, $tmp)){
$tmp[] = $val;
}else{
$tmp2[] = $val;
}
}
$finalArr = array_merge($tmp, $tmp2); // your desired output
Try this:
$arr = array( 2, 1, 3, 1, 5, 2,2);
$groups = array(array());
foreach($arr as $a) {
$found = false;
foreach($groups as &$g) {
if(in_array($a, $g)) {
continue;
}
$g[] = $a;
$found = true;
break;
}
if(!$found) {
$groups[] = array($a);
}
}
foreach($groups as &$g) {
sort($g);
}
$result = array();
foreach($groups as &$g) {
$result = array_merge($result, $g);
}
var_dump($result);
it will work for unlimited duplicates
You can try it here
Related
I have an $array and a $number, and I want to find the smallest combination (least number of elements) of the $array's elements, which sums to the $number, but I can't figure out how to do this with PHP code.
Test cases:
$array = [
'a' => '1',
'b' => '3',
'c' => '5',
'd' => '5',
'e' => '1',
'f' => '2',
'g' => '2',
];
If $number = 10, output should be 'c', 'd'
If $number = 1, output should be either 'a' or 'e'
If $number = 4, output should be either 'a', 'b' or 'b', 'e' or 'f', 'g'
If $number = 9 output should be 'a', 'b', 'c' or 'a', 'b', 'd' or 'c', 'f', 'g' etc.
How can I write this in code?
try this ( and use Recursive Algorithm )
<?php
$array= array("a"=>"1", "b"=>"3", "c"=>"5", "d"=>"5", "e"=>"1", "f"=>"2","g"=>"2");$num=6;
foreach ($array as $key => $value) {
if ($value==$num){
echo $key."=>".$value."<br>";
}
echo "-----------------"."<br>";
foreach( $array as $key1 => $value1) {
if($key1 > $key){
if(sumval($value,$value1)==$num){
echo $key."=>".$key1."<br>";
}
elseif(sumval($value,$value1)<$num){
$total=sumval($value,$value1);
foreach( $array as $key2 => $value2) {
if($key2 > $key1){
if(sumval($total,$value2)==$num){
echo $key."=>".$key1."=>".$key2."<br>";
}
}
}
}
}
}
}
function sumval($a,$b){
return $a+$b;
}
?>
You can try something like this
<?php
$array = ["a"=>"1", "b"=>"3", "c"=>"5", "d"=>"5", "e"=>"1", "f"=>"2", "g"=>"2"];
$new = $array;
$number = 19;//Change here to check all condition
$flag = false;
if(array_sum($new) == $number){
$temp = array_keys($new);
echo implode(",",$temp);
$flag = true;
exit;
}
if($flag)
exit;
foreach($array as $key=>$value){
if($value == $number){
echo $key."\n";
$flag = true;
exit;
}
}
if($flag)
exit;
foreach($array as $key=>$value){
$new = $array;
array_pop($new);
foreach($new as $key2=>$value2){
if($key!=$key2){
if(($value + $value2) == $number){
echo "$key , $key2 \n";
$flag = true;
exit;
}
}
}
}
if($flag)
exit;
$new = $array;
foreach($array as $key1=>$value1){
foreach($array as $key=>$value){
$new = $array;
unset($new[$key]);
if(array_sum($new) == $number){
$temp = array_keys($new);
echo implode(",",$temp);
exit;
}
array_pop($new);
}
array_pop($array);
}
?>
Live demo : https://eval.in/897632
Try this?
<?php
$array= array("a"=>"1", "b"=>"3", "c"=>"5", "d"=>"5", "e"=>"1", "f"=>"2", "g"=>"2");
$num = 4;
foreach ($array as $key => $value) {
$n1 = (int) $value;
if ($n1 === $num) {
echo $key.'<br/>';
break;
}
if ($n1 < $num) {
$n2 = $num - $n1;
if ($n2Key = isN2Exists("$n2", $array)) { // this probably can also be done using some PHP built-ins, but I just couldnt find the right one
echo "$key,$n2Key <br/>";
}
}
}
function isN2Exists($value, $array) {
foreach ($array as $k => $v) {
if ($v === $value) {
return $k;
}
}
return false;
}
This wont work if you need more than 2 numbers. For example, if the number is 9, you can not produce 9 with two numbers in your array. You need a,b,c or c,f,g. If you want it that way I think best way to do is to use recursion.
Update
If you want to do it through recursion, please try the following code. This should give you the exact output you are looking for:
<?php
$array= array("a"=>"1", "b"=>"3", "c"=>"5", "d"=>"5", "e"=>"1", "f"=>"2", "g"=>"2");
$num = 9;
function getLeastNumbers($num, $array, $sum = 0, $level = '', $resultSet = [], $combination = []) {
if ($sum > $num) {
return false;
}
foreach ($array as $key => $value) {
$n1 = (int) $value;
if (($n1 + $sum) == $num) {
$newCombination = $combination;
$newCombination[] = $key;
sort($newCombination);
$resultSet[] = $newCombination;
}
$combinationToSend = $combination;
$combinationToSend[] = $key;
sort($combinationToSend);
$array2 = $array;
unset($array2[$key]);
if ($return = getLeastNumbers($num, $array2, $n1 + $sum, "$level .", $resultSet, $combinationToSend)) {
$resultSet = array_unique(array_merge($resultSet, $return), SORT_REGULAR);
}
}
return $resultSet;
}
$list = getLeastNumbers($num, $array);
foreach($list as $item) {
$length = count($item);
$finalArray[$length][] = $item;
}
print_r($finalArray[min(array_keys($finalArray))]);
I am adding other value array inside foreach loop which working fine for me.
$i = true;
$array = array('red', 'blue');
foreach($array as $key => & $value) {
echo $value . '<br />';
if ($i === true) {
$others = array('white', 'yellow');
foreach($others as $key => & $other_value) {
$array[] = $other_value;
}
}
$i = false;
}
Output
red
blue
white
yellow
but i want to reshuffle array value inside foreach loop need output like below
red
white
yellow
blue
You won't be able to do it on $array without some serious array_slice()ing. So, just assign to another array $result and you will get the $other array inserted between the first and second elements of $array:
$i = true;
$array = array('red', 'blue');
foreach($array as $value) {
$result[] = $value; // here...
if ($i === true) {
$others = array('white', 'yellow');
foreach($others as $other_value) {
$result[] = $other_value; // and here...
}
}
$i = false;
}
If needed (for whatever reason) $array = $result;
A cool solution would be like this:
$array = array('red', 'blue');
$others = array('white', 'yellow');
$temp = array_combine($array,$others);
$final = array();
foreach($temp as $key => $value) {
array_push($final,$key,$value);
}
$array = $final;
$i = true;
$array = array('red', 'blue');
foreach($array as $key => & $value) {
echo $value . '<br />';
if ($i === true) {
$a1= $array;
$a2= array($value);
$result=array_diff($a1,$a2);
$others = array('white', 'yellow');
$array = array_merge($others,$result);
}
$i = false;
}
see output
I have an array like that
$products = array(array(354),array(1),array(375),array(1),array(344),array(2));
and i want to achieve array like that
$arrProducts= array(array('product_id'=>354,'qty'=>1),array('product_id'=>375,'qty'=>1),array('product_id'=>344,'qty'=>2));
I achieved this array using this code
foreach($products as $val)
{
$abc[] =$val[0];
}
for($i=0;$i<count($abc);$i++)
{
if($i%2==0)
{
$newarr[]['product_id'] = $abc[$i];
}
else{
$newarr[]['qty'] = $abc[$i];
}
}
for($j=0;$j<count($newarr);$j++)
{
if($j%2==0)
{
$arrProducts[] = array_merge($newarr[$j],$newarr[$j+1]);
}
else{
continue;
}
}
echo '<pre>';
print_r($arrProducts);
but i think my way to get this array is too long so how can i get this array in short way using some array functions or should i use this code?
You can use array_chunk in this case if this is always by twos, and combine it with array_combine():
$products = array(array(354),array(1),array(375),array(1),array(344),array(2));
$products = array_chunk($products, 2);
$arrProducts = array();
$keys = array('product_id', 'qty');
foreach($products as $val) {
$arrProducts[] = array_combine($keys, array(reset($val[0]), reset($val[1])));
}
echo '<pre>';
print_r($arrProducts);
Another alternative would be:
$products = array(array(354),array(1),array(375),array(1),array(344),array(2));
$keys = array('product_id', 'qty');
$arrProducts = array_map(function($e) use ($keys) {
return array_combine($keys, array_map('reset', $e));
}, array_chunk($products, 2));
This will yield the same result.
Consume two array elements on each iteration:
$arrProducts = array();
$inputLength = count($products);
for ($i = 0; $i < $inputLength; $i += 2) {
$arrProducts[] = array('product_id' => $products[$i][0], 'qty' => $products[$i+1][0]);
}
$i=1;
$j=0;
foreach($products as $val)
{
if(($i%2) == 0)
{
$abc[$j]['qty'] =$val[0];
$j++;
}
else
{
$abc[$j]['product_id'] =$val[0];
}
$i++;
}
I would like to test if the key of an associative array exist in my $_POST.
my $_POST is like that:
$_POST["balle"]["x"] = 5;
$_POST["balle"]["y"] = 5;
$_POST["balle"]["z"] = 5;
or like that by example:
$_POST["p1"][1]["vit"] = 7;
$_POST["p1"][1]["angle"] = 32;
$_POST["p2"][2]["vit"] = 17;
$_POST["p2"][2]["angle"] = 2;
the values don't matter but I must check how are my $_POST keys.
I don't understand how i can test recursivly that because the $_POST can change and have differents forms.
I have try this:
function Check_post($new, $arr)
{
echo "Init<br/>";
$res = true;
if (is_array($new))
{
foreach ($new as $key => $value)
{
if (!in_array($key, $arr))
{
echo "Fail $key";
print_r($arr);
return (false);
}
$res = $res & Check_post($new[$key], $arr[$key]);
}
}
else
$res = in_array($new, $arr);
echo "MY RESULT";
var_dump($res);
return ($res);
}
$b = array();
$b["balle"] = array("x", "y", "z");
$post = array();
$post["balle"] = array();
$post["balle"]["x"] = 50;
$post["balle"]["y"] = 50;
$post["balle"]["z"] = 50;
echo "<pre>";
print_r($b);
echo "</pre><pre>";
print_r($post);
echo "</pre>";
Check_post($b, $post);
but i got "Fail balle". my $post variable is to simulate the real $_POST and for make it easier to test.
EDIT:
The function should work like that:
1) test if "balle" exist in $post
2) "balle" exist so recursive call
3) test if "x" exist in $post["balle"](recursive)
4) test if "y" exist in $post["balle"](recursive)
5) test if "z" exist in $post["balle"](recursive)
6) all existe so $res = true
EDIT:
I finaly editet the whole function:
function Check_post($needle, $haystack)
{
if(is_array($needle)){
foreach ($needle as $key => $element){
$result = true;
if($result = (array_key_exists($key, $haystack) || array_key_exists($element, $haystack))){
$key = (isset($haystack[$key]) ? $key : $element);
if(is_array($haystack[$key]))
$result = Check_post($element, $haystack[$key]);
}
if(!$result){
return false;
}
}
return $result;
}else {
return array_key_exists($needle, $haystack);
}
}
Now it should work as you want it
Example:
$_POST["balle"]["x"] = 5;
$_POST["balle"]["y"] = 5;
$_POST["balle"]["z"] = 5;
$b = array();
$b["balle"] = array("x", "y", "z");
var_dump(Check_post($b, $_POST)); //returns true
$b["balle"] = array("x", "y", "z", "b");
var_dump(Check_post($b, $_POST)); //returns false
The in_array function you're using checks if $key is contained in $arr as a value. If I got you right, you want to check if there is the same key in $arr instead. Use array_key_exists($key, $arr) for this.
Try this
$_POST["p1"][1]["vit"] = 7;
$_POST["p1"][1]["angle"] = 32;
$_POST["p2"][2]["vit"] = 17;
$_POST["p2"][2]["angle"] = 2;
$needle = "2";
$samp = Check_post($_POST,$needle);
echo $samp;
function Check_post($array,$needle)
{
if(is_array($array))
{
foreach($array as $key=>$value)
{
if($key == $needle)
{
echo $key." key exists ";
}
else
{
if(is_array($value))
{
check_post($value,$needle);
}
}
}
}
}
Demo
I need to get all the combinations and permutations of an array of array of values. See snippet for example:
$a = array(
1,
2
);
$b = array(
'foo',
'bar'
);
$params = array();
$params[] = $a;
$params[] = $b;
// What to do to $params so I can get the following combinations/permutations?
// 1,foo
// 2,foo
// 1,bar
// 2,bar
// foo,1
// bar,1
// foo,2
// bar,2
Keep in mind that the $params can be any size and the items in it can also be any size.
function all($array, $partial, &$result) {
if ($array == array()) {
$result[] = implode(',', $partial);
return;
}
for($i=0; $i<count($array);$i++) {
$e = $array[$i];
$a = $array;
array_splice($a, $i, 1);
foreach($e as $v) {
$p = $partial;
$p[] = $v;
all($a, $p, $result);
}
}
}
Test:
$a = array(1, 2, 3);
$b = array('foo', 'bar');
$c = array('a', 'b');
$params = array($a, $b, $c);
$result = array();
all($params, array(), $result);
print_r($result);
Note: if there is a chance for duplicates (arrays contain the same values) you can check for duplicates before inserting into the $result.
Here is my solution. It should work with any number of associative arrays, even if they contained nested associative arrays.
<?php
$a = array(1,2,3);
$b = array('foo','bar','baz', array('other','other2',array('other3','other4')));
$params = array();
$params[] = $a;
$params[] = $b;
$elements = array();
foreach($params as $param) {
addElement($param,$elements);
}
function addElement($arg,&$result) {
if(!is_array($arg)) {
$result[] = $arg;
} else {
foreach($arg as $argArray) {
addElement($argArray,$result);
}
}
}
for($i=0; $i<count($elements); $i++) {
$curElement = $elements[$i];
for($j=0; $j<count($elements); $j++) {
if($elements[$j] != $curElement) {
$final_results[] = $curElement.','.$elements[$j];
}
}
}
print_r($final_results);
?>
http://codepad.viper-7.com/XEAKFM
Here's a possible solution codepad...
$array = array(
0 => array(
'foo',
'bar'
),
1 => array(
1,
2,
3
),
2 => array(
'x',
'y',
'z'
),
3 => array(
7,
8,
9
)
);
array_permutations($array, $permutations);
print_r($permutations);
public function array_permutations($array, &$permutations, $current_key = 0, $current_subkey = 0)
{
if(!isset($array[$current_key][$current_subkey]))
{
return;
}
$current_val = $array[$current_key][$current_subkey];
foreach($array as $array_key => $row)
{
foreach($row as $row_key => $sub_val)
{
if($array_key === $current_key)
{
if($row_key !== $current_subkey)
{
$permutations[] = $current_val . ', ' . $sub_val;
}
}
else
{
$permutations[] = $current_val . ', ' . $sub_val;
}
}
}
$next_key = ($current_subkey == (count($array[$current_key]) - 1)) ? $current_key + 1 : $current_key;
$next_subkey = ($next_key > $current_key) ? 0 : $current_subkey + 1;
array_permutations($array, $permutations, $next_key, $next_subkey);
}
Try this out, hope this helps
$a = array(
1,
2,
4
);
$b = array(
'foo',
'bar',
'zer'
);
$c = array(
'aaa',
'bbb'
);
$params = array();
$params[] = $a;
$params[] = $b;
$params[] = $c;
$sizeofp = count($params);
for($i=0 ; $i < $sizeofp ; $i++){
foreach ($params[$i] as $paramA) {
for($j=0 ; $j < $sizeofp ; $j++){
if($j == $i){
continue;
}
foreach($params[$j] as $paramB){
echo "\n".$paramA.",".$paramB;
}
}
}
}