This is the code to display multi dimension with array
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<?php
$numberArray = array(
array(1, 2, 3, 4, 7, 6),
array(2, 3, 1, 0, 5)
);
function printTable($numberArray) {
// Placeholder
$result = [];
// Setup the multiplication
foreach ($numberArray[1] as $key1 => $value1) {
$tmp = array($value1); // add index y-axis
foreach ($numberArray[0] as $key0 => $value0) {
$tmp[] = $value0 * $value1;
}
$result[] = $tmp;
}
// Add index the x-axis
array_unshift($result, array_merge(array(" "), $numberArray[0]));
// Loop through the $result array and display the table
echo "<table border='1'>";
foreach ($result as $key => $value) {
echo "<tr>";
foreach ($value as $k => $v) {
if ($k == 0 || $key == 0) {
echo sprintf("<td><b>%s</b></td>", $v);
continue;
}
echo "<td>$v</td>";
}
echo "</tr>";
}
echo "</table>";
}
?>
</body>
</html>
Example of output: https://gyazo.com/2a0a5c07ac75f285f6b8a4631d5b723c
How to display the multi dimension with array and inside the answer will be multiply between numbers.
Looking at the links to the screenshots you provided, maybe this setup can help you:
<?php
$numberArray = array(
array(1, 2, 3, 4, 7, 6),
array(2, 3, 1, 0, 5)
);
function printTable($numberArray)
{
// Placeholder
$result = [];
// Setup the multiplication
foreach ($numberArray[1] as $key1 => $value1) {
$tmp = array($value1); // add index y-axis
foreach ($numberArray[0] as $key0 => $value0) {
$tmp[] = $value0 * $value1;
}
$result[] = $tmp;
}
// Add index the x-axis
array_unshift($result, array_merge(array(" "), $numberArray[0]));
// Loop through the $result array and display the table
echo "<table border='2'>";
foreach ($result as $key => $value) {
echo "<tr>";
foreach ($value as $k => $v) {
if ($k == 0 || $key == 0) {
echo sprintf("<td><b>%s</b></td>", $v);
continue;
}
echo "<td>$v</td>";
}
echo "</tr>";
}
echo "</table>";
}
Related
I'm trying to merge multiple arrays with same keys and add their values if keys exist, if not add a new object. Could not get the logic right on this
these are samle arrays
[{"2":"90"},{"12":"400"},{"25":"750"},{"0":"50"}]
[{"1":"100"},{"23":"200"},{"12":"1000"},{"0":"5"}]
and the expected output is
[{ {"2":"90"},{"12":"1400"},{"25":"750"},{"0":"55"},{"1":"100"},{"23":"200"}]
This is php code i have used
while($row = $result->fetch_assoc())
{
if ($i==0)
{
$rowOut = $row;
$i++;
}else
{
foreach($rowOut as $key1 => $value1) {
foreach($row as $key => $value)
{
if($key == $key1){
(int)$rowOut->$value1 = (int)$value + (int)$value1;
}
}
}
}
}
not the most elegant solution, but it works
$a = [2=>90,12=>400,25=>750,0=>50] ;
$b = [1=>100,23=>200,12=>1000,0=>5];
$ak = array_keys($a);
$bk = array_keys($b);
$ck = array_intersect($ak,$bk);
$out = [];
foreach ($ck as $key => $value)
{
$out[$value] = $a[$value] + $b[$value];
unset($a[$value]);
unset($b[$value]);
}
foreach ($a as $key => $value)
{
$out[$key] = $value;
}
foreach ($b as $key => $value)
{
$out[$key] = $value;
}
var_dump($out);
You may concat the two arrays and use reduce to construct the new array.
demo
<?php
$array1 = [
["2" => "90"],
["12" => "400"],
["25" => "750"],
["0" => "50"]
];
$array2 = [
["1" => "100"],
["23" => "200"],
["12" => "1000"],
["0" => "5"]
];
$concat = [...$array1, ...$array2];
$reduce = array_reduce($concat, function ($carry, $item) {
$key = array_keys($item)[0];
if (isset($carry[$key])) {
$carry[$key][$key] += $item[$key];
} else {
$carry[$key] = [$key => $item[$key]];
}
$carry[$key][$key] = (string)$carry[$key][$key];
return $carry;
}, []);
$output = array_values($reduce);
echo var_dump($output);
I want to limit every array to strings with 15 characters or less. I have tried this code, but it does not work:
$a = [
"name1" => ['Dewa','Aditya','Pratama'],
"name2" => ['Brian','Dzikri','Ramadhan'],
];
$result_shortdes = "";
foreach ($a as $values) {
foreach ($values as $value) {
if(strlen($result_shortdes) + strlen($value) <= 15)
{
$result_shortdes .= "$value,";
}
}
}
echo '<pre>';
print_r($result_shortdes);
echo '<pre>';
My expected output is like this:
1. Dewa,Aditya,
2. Brian,
Every time you go to the next name, you need to reset result_shortdes to count the name length again, place the variable inside the first loop like this:
foreach ($a as $values) {
$result_shortdes = "";
foreach ($values as $value) {
if(strlen($result_shortdes) + strlen($value) <= 15)
{
$result_shortdes .= "$value,";
}
}
echo '<pre>';
print_r($result_shortdes);
echo '<pre>';
}
you can use $result_shortdes for length and $result to store result like below
$a = [
"name1" => ['Dewa','Aditya','Pratama'],
"name2" => ['Brian','Dzikri','Ramadhan'],
];
$result_shortdes = "";
$result = [];
foreach ($a as $values) {
$result_shortdes = "";
foreach ($values as $value) {
if(strlen($result_shortdes) + strlen($value) <= 15)
{
$result_shortdes .= "$value,";
}else{
$result[] = $result_shortdes;
break;
}
}
}
echo '<pre>';
print_r($result);
echo '<pre>';
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 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
This is the code of accept input from user and display array and multiplication and put it in table form.
<?php
if(isset($_POST['submit']))
{
$n1 = $_POST['num1'];
$n2 = $_POST['num2'];
}
else
{
$n1 = 0;
$n2 = 0;
}
function UniqueRandomNumbersWithinRange($min, $max, $quantity) {
$numbers = range($min, $max);
shuffle($numbers);
return array_slice($numbers, 0, $quantity);
}
$numberArray = array(
UniqueRandomNumbersWithinRange(1,10,$n1),
UniqueRandomNumbersWithinRange(1,10,$n2))
?>
<form action="" method="post">
<input type="text" name="num1" placeholder="value 1"><br>
<input type="text" name="num2" placeholder="value 2"><br>
<input type="submit" name="submit">
</form>
<?php
printTable($numberArray); //panggilan function apa yg nk tunjuk
function printTable($numberArray) {
// Placeholder
$result = [];
// Setup the multiply
foreach ($numberArray[1] as $key1 => $value1) {
$tmp = array($value1); // add index y-axis
foreach ($numberArray[0] as $key0 => $value0) {
$tmp[] = $value0 * $value1;
}
$result[] = $tmp;
}
// Add index the x-axis
array_unshift($result, array_merge(array(" "), $numberArray[0]));
// display the result into table form
echo "<table border='1' align='center'>";
foreach ($result as $key => $value) {
echo "<tr>";
foreach ($value as $k => $v) {
if ($k == 0 || $key == 0) {
echo sprintf("<td><b>%s</b></td>", $v);
continue;
}
echo "<td>$v</td>";
}
echo "</tr>";
}
echo "</table>";
}
?>
Here can accept insert from user and auto generate number in array form which means user enter 5 in the textbox1 and 6 in the textbox2, it will generate number 3,4,5,2,1 and 2,3,4,1,2,3.
How I can capture this number put inside
$numberArray = array(
array($display1),
array($display2)
);