To calculate the sum of values based on the input and match it with names in an array
$input = '500';
$array1 = array("200" => 'jhon',"300" => 'puppy',"50" => 'liza',
"150" => 'rehana',"400" => 'samra',"100" => 'bolda',);
need answer like this output
jhon,puppy and bolda,rehana
This code creates an array $data that contains names and their respective values. It then uses a foreach loop to iterate through the array and subtract the value of each name from the input until the input becomes zero. The names of all the values that were subtracted from the input are stored in an array $names. Finally, if the array $names is not empty, the names are echoed using implode separated by "and". If the array is empty, it means no match was found and a message "No match found" is echoed.
So I'm going to go out on a guess here. (this sounds like cheating on homework lmao).
You need to output pairs of names where the two names add upto 500 (the input).
This probably wont be the most optimal solution, but it should be a solution that works?
$input = 500;
// using shorthand array formatting
$array1 = [
200 => 'jhon',
300 => 'puppy',
50 => 'liza',
150 => 'rehana',
400 => 'samra',
100 => 'bolda'
];
// create an array that holds names we have already processed.
$namesProcessed = [];
// loop over the names trying to find a compatible partner
foreach ($array1 as $points => $name) {
foreach ($array1 as $pointsPotentialPartner => $namePotentialPartner) {
// Don't partner with yourself...
if ($name == $namePotentialPartner) {
continue;
}
// Don't partner with someone that has already been processed.
if (in_array($namePotentialPartner, $namesProcessed)) {
continue;
}
// test if the two partners add up to the input
if ($input == ($points + $pointsPotentialPartner)) {
// if this is the first partner set, don't put in 'and'
if (count($namesProcessed) == 0) {
echo $name . ', ' . $namePotentialPartner;
} else {
echo ' and ' . $name . ', ' . $namePotentialPartner;
}
$namesProcessed[] = $name;
$namesProcessed[] = $namePotentialPartner;
}
}
}
Hope this helps.
Related
I'm probably just overlooking the obvious but I'd like to blame it on the fact that I'm new to PHP.
I have some number of arrays being returned with similar information but differing amounts of it.
I'll put some example arrays below:
(t1-s1-1=1, t1-s1-2=1, t1-s2-1=1, t1-s2-2=1)
(t2-s1-1=1, t2-s2-1=2, t2-s2-2=1)
(t3-s1-1=1, t3-s2-1=1, t3-s3-1=1, t3-s3-2=3)
So I would like to make a table out of this information. Something like this:
test .. s1-1 .. s1-2 .. s2-1 .. s2-2 .. s3-1 .. s3-2
t1 ........1 .....1 ..........1 ....... 1.........1..........1
t2 ........1 .......X..........1..........1........1..........1
t3 ........1 .......X..........1..........X........1..........1
( where x is something that wasn't there. )
So every array has an s1 but could have s1-1, s1-2, s1-3 or simply s1-1. That creates very different sized arrays.
The problem is that each array can have wildly different information and because they are Indexed arrays instead of Associative arrays I'm not sure how to best equalize them. I can't consistently say index 3 is s1-3 or something else.
I can't just loop through manually because I never know where a gap will appear. I can't look for specific indexes because the arrays aren't associative so the titles are built into the value and I don't know how to access them separately.
Any good ideas out there that maybe a newbie is overlooking? I'm open to non-tabular display ideas as well as long as I can easily sort and display the information.
Thanks
I'm assuming your original arrays contain values as string, so for instance, in PHP syntax, they look like:
['t1-s1-1=1', 't1-s1-2=1', 't1-s2-1=1', 't1-s2-2=1']
Basically, you should create a bi-dimensional array:
go through all arrays and by using a regex extract the different parts, that is, for the first element in the array above: t1 (the index for the first level in the bi-dimensional array), s1-1 (the index for the second level in the bi-dimensional array) and the value 1
insert the value in the bi-dimensional array
keep in a separate array, let's call it allColumns every second index above (sx-y), even you will have duplicate values you can, at the end, delete those duplicate and order it alphabetically
After that, you will have all the value in the bi-dimensional array but you still miss the gaps, so what you can do it iterate over the bi-dimensional array, and for every dimension tz (t1, t2,...), go through for all the values stored in allColumns and if you don't find the entry for that sx-y in the bi-dimensional array for that tz, add it with value x (or probably with value = 0)
I think an example can clarify the above:
// arrays of arrays, I don't know how you receive the data
$arrays = [
['t1-s1-1=1', 't1-s1-2=1', 't1-s2-1=1', 't1-s2-2=1'],
['t2-s1-1=1', 't2-s2-1=2', 't2-s2-2=1'],
['t3-s1-1=1', 't3-s2-1=1', 't3-s3-1=1', 't3-s3-2=3']
];
// bi-dimensional array
$output = [];
// it will store all columns you find in the $arrays entry
$allColumns = [];
// iterate for every array you receive, i.e. ['t1-s1-1=1', 't1-s1-2=1', 't1-s2-1=1', 't1-s2-2=1']
foreach ($arrays as $array) {
// iterate over every element in the array: 't1-s1-1=1', 't1-s1-2=1', 't1-s2-1=1' and 't1-s2-2=1'
foreach ($array as $item) {
// extract the parts on every element: $matches is an array containing the different parts
preg_match('/^(t\d+)-(s\d+-\d+)=(\d+)/', $item, $matches);
/**
* $matches[0] would contains the element if matched: 't1-s1-1=1'
* $matches[1] would contains 't1' if matched
* $matches[2] would contains 's1-1' if matched
* $matches[2] would contains 1 (integer) if matched
*/
if (!empty($matches)) {
$output[$matches[1]][$matches[2]] = $matches[3];
$allColumns[] = $matches[2];
}
}
}
// clean duplicates
$allColumns = array_unique($allColumns);
// sort values alphabetically
sort($allColumns);
// iterate over the just created bi-dimensional array
foreach ($output as $row => $columns) {
// iterate for all columns collected before
foreach ($allColumns as $column) {
// if one of column in 'allColumns' doesn't exit in $output you added in the correct place adding a zero value
if (!in_array($column, array_keys($columns))) {
$output[$row][$column] = 0;
}
}
}
To print the output you should only iterate over $ouput
This will be the array internally:
(
[t1] => Array
(
[s1-1] => 1
[s1-2] => 1
[s2-1] => 1
[s2-2] => 1
[s3-1] => 0
[s3-2] => 0
)
[t2] => Array
(
[s1-1] => 1
[s2-1] => 2
[s2-2] => 1
[s1-2] => 0
[s3-1] => 0
[s3-2] => 0
)
[t3] => Array
(
[s1-1] => 1
[s2-1] => 1
[s3-1] => 1
[s3-2] => 3
[s1-2] => 0
[s2-2] => 0
)
)
It exists other ways to implement the above, like skip the step where you fill the gaps and do it on the fly, ...
Updated
The simplest way to display the results in a HTML page is by embedding a php script to iterate over the associative array and compose the HTML table (I encourage you to study and research MVC to separate logic from the view)
<!DOCTYPE html>
<?php
// arrays of arrays, I don't know how you receive the data
$arrays = [
['t1-s1-1=1', 't1-s1-2=1', 't1-s2-1=1', 't1-s2-2=1'],
['t2-s1-1=1', 't2-s2-1=2', 't2-s2-2=1'],
['t3-s1-1=1', 't3-s2-1=1', 't3-s3-1=1', 't3-s3-2=3']
];
// bi-dimensional array
$output = [];
// it will store all columns you find in the $arrays entry
$allColumns = [];
// iterate for every array you receive, i.e. ['t1-s1-1=1', 't1-s1-2=1', 't1-s2-1=1', 't1-s2-2=1']
foreach ($arrays as $array) {
// iterate over every element in the array: 't1-s1-1=1', 't1-s1-2=1', 't1-s2-1=1' and 't1-s2-2=1'
foreach ($array as $item) {
// extract the parts on every element: $matches is an array containing the different parts
preg_match('/^(t\d+)-(s\d+-\d+)=(\d+)/', $item, $matches);
/**
* $matches[0] would contains the element if matched: 't1-s1-1=1'
* $matches[1] would contains 't1' if matched
* $matches[2] would contains 's1-1' if matched
* $matches[2] would contains 1 (integer) if matched
*/
if (!empty($matches)) {
$output[$matches[1]][$matches[2]] = $matches[3];
$allColumns[] = $matches[2];
}
}
}
// clean duplicates
$allColumns = array_unique($allColumns);
// sort values alphabetically
sort($allColumns);
// iterate over the just created bi-dimensional array
foreach ($output as $row => $columns) {
// iterate for all columns collected before
foreach ($allColumns as $column) {
// if one of column in 'allColumns' doesn't exit in $output you added in the correct place adding a zero value
if (!in_array($column, array_keys($columns))) {
$output[$row][$column] = 0;
}
}
}
?>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Table Page</title>
</head>
<body>
<table>
<thead>
<?php
echo '<tr><th>Test</th>';
foreach ($allColumns as $head) {
echo sprintf('<th>%s</th>', $head);
}
echo '</tr>';
?>
</thead>
<tbody>
<?php
foreach ($output as $key => $columns) {
echo sprintf('<tr><td>%s</td>', $key);
foreach ($columns as $column) {
echo sprintf('<td>%s</td>', $column);
}
echo '</tr>';
}
?>
</tbody>
</table>
</body>
</html>
Try the following:
$final_array = array();
$temp_array = array();
foreach ($t1 as $t) {
$isin = 0;
$expression = substr($t, 0, strpos($t, "="));
$expression = str_replace("t1-", "" , $expression)
$value = substr($t, strpos($t, "=") + 1);
for ($i = 0; $i < 3; $i++) {
foreach ($x = 0; $x < 3; $x++) {
if ($expression == "s{$i}-{$x}") {
$isin = 1;
array_push($temp_array, $value);
}
}
}
if ($isin == 0) { array_push($temp_array, "X"); }
}
array_push($final_array, $temp_array);
It's not a great solution because you're choosing to do this in a really odd way but you should see the gist of what how to get what you want from this example.
I have the following array.
$arr = array('foo','bar','foo-bar','abc','def','abc-def','ghi','abc-def-ghi');
I'm given a new string to decide to add to the array or not. If the string is already in the array, don't add it. If it is not in the array in its current form, but in a flipped word form is found, don't add it.
How should I accomplish this?
Examples:
'foo' —-> N - Do NOT add, already found
'xyz' —-> Y - Add, this is new
'bar-foo' —-> N - Do NOT add, already found in the flipped form 'foo-bar'
'ghi-jkl' —-> Y - Add, this is new
What do you recommend?
If you want to exclude items whose elements ('abc','ghi', etc.) are contained in another order and not only reversed, you could do:
$arr = array('foo','bar','foo-bar','abc','def','abc-def','ghi','abc-def-ghi');
function split_and_sort($str) {
$partsA = explode('-', $str);
sort($partsA);
return $partsA;
}
$arr_parts = array_map('split_and_sort', $arr);
$tests = array('foo','xyz','bar-foo','ghi-jkl');
$tests_parts = array_map('split_and_sort', $tests);
foreach($tests_parts as $test) {
if( !in_array($test, $arr_parts)) {
echo "adding: " . join('-', $test) . "\n";
$arr[] = join('-', $test);
}
else {
echo "skipping: " . join('-', $test) . "\n";
}
}
var_export($arr);
which outputs:
skipping: foo
adding: xyz
skipping: bar-foo
adding: ghi-jkl
array (
0 => 'foo',
1 => 'bar',
2 => 'foo-bar',
3 => 'abc',
4 => 'def',
5 => 'abc-def',
6 => 'ghi',
7 => 'abc-def-ghi',
8 => 'xyz',
9 => 'ghi-jkl',
)
Heres a suggestions on one way you can try...
for each string in $arr, reverse it as push into another array called $rev_arr
then...
$new_array = array();
foreach ($arr as $arr_1) $new_array[$arr_1] = true; // just set something
foreach ($rev_arr as $arr_2) $new_array[$arr_2] = true; // do also for reverse
now you can check what you want to do based on
if ( isset($new_arr[ $YOUR_TEST_VARIABLE_HERE ]) ) { // match found
}
I have an array of temperature data by hour. Some hours have zero data instead of a temp. When graphing using Google Charts, the zero causes the line graph to plummet. My temporary fix was to replace the zero values with null, causing a break in the line graph. The ideal solution would be to take the values on either side of the zero, and average them. The array is in order by hour. Help?
$array = array(
"1AM" => "65",
"2AM" => "66",
"3AM" => "68",
"4AM" => "68",
"5AM" => "68",
"6AM" => "0",
"7AM" => "70",
"8AM" => "71",
"9AM" => "71",
"10AM" => "73",
);
Here's my script replacing the 0's with nulls:
$array = array ();
foreach($parsed_json->history->observations as $key => $value) {
$temp = (int)$value->tempi;
if ($temp==0) {
str_replace(0, null, $temp);
}
$hour = $value->date->hour;
$array[$hour] = $temp;
};
This Example would work great if the data was mine, but alas, it's from a JSON feed.
Would I use an array_walk() sort of deal? How would I reference the current place in the array? Any help is appreciated!
I would scratch out the null portion, and just foreach-loop through the final array.
So, change your current code to:
$array = array ();
foreach($parsed_json->history->observations as $key => $value) {
$temp = (int)$value->tempi;
}
$hour = $value->date->hour;
$array[$hour] = $temp;
And add this below it:
foreach($array as $hour => $temp){
if($temp == "0"){
$numHour = $hour[0];
$hourPlus = ($numHour + 1) . "AM";
$hourMinus = ($numHour - 1) . "AM";
$valuePlus = $array[$hourPlus];
$valueMinus = $array[$hourMinus];
$average = ($valuePlus + $valueMinus)/2;
$array[$hour] = $average;
}
}
?>
This of course assumes that the values on either side of the zero are also not zero. You may want to add a check for that somewhere in there.
Tested and proven method.
Couldn't you do something along the lines of:
str_replace(0, ((($key-1)+($key+1))/2), $temp);
Where $key is array position, take the value before 0 and after 0 add them and divide them by 2 to get the average.
I'll let you sort out what happens if first, last or consecutive values are 0.
$the_keys=array_keys($array);
foreach($the_key as $index=>$key)
{
if($array[$key]==0)
{
$array[$key]=($array[$the_key[$index-1]]+$array[$the_key[$index+1]]/2);
}
}
i got problem with my code and hopefully someone able to figure it out. The main purpose is to sort array based on its value (then reindex its numerical key).
i got this sample of filename :
$filename = array("index 198.php", "index 192.php", "index 144.php", "index 2.php", "index 1.php", "index 100.php", "index 111.php");
$alloutput = array(); //all of index in array
foreach ($filename as $name) {
preg_match('#(\d+)#', $name, $output); // take only the numerical from file name
array_shift($output); // cleaned. the last code create duplicate numerical in $output,
if (is_array($output)) {
$alloutput = array_merge($alloutput, $output);
}
}
//try to check the type of every value in array
foreach ($alloutput as $output) {
if (is_array($output)) {
echo "array true </br>";
} elseif (is_int($output)) {
echo "integer true </br>";
} elseif (is_string($output)) { //the numerical taken from filename always resuld "string".
echo "string true </br>";
}
}
the output of this code will be :
Array
(
[0] => 198
[1] => 192
[2] => 144
[3] => 2
[4] => 1
[5] => 100
[6] => 111
)
i have test every output in array. It's all string (and not numerical), So the question is how to change this string to integer, so i can sort it from the lowest into the highest number ?
the main purpose of this code is how to output array where it had been sort from lowest to highest ?
preg_match will keep the matched part in $outpu[1], so you can make use of that to convert the string to int and then add it to your alloutput array.
foreach ($filename as $name) {
preg_match('#(\d+)#', $name, $output);
$alloutput[] = intval($output[1]);
}
Use intval
$number_string = '14';
$number = intval('14');
With intval you can specify also the basis. If the number is decimal, hower, you can also use
$number = (int) $number_string;
I have an array like
$myArray =array
(
"0"=>array("dogs",98),
"1"=>array("cats",56),
"2"=>array("buffaloes",78)
)
How can I get a key by providing a value?
e.g. if i search for "buffaloes" array_search may return "2".
Thanks
$myArray =array
(
"0"=>array("dogs",98),
"1"=>array("cats",56),
"2"=>array("buffaloes",78)
);
function findInArray($term, $array) {
foreach($array as $key => $val) {
if(in_array($term, $val, true)) {
return $key;
}
}
}
echo findInArray('buffaloes', $myArray); // 2
echo findInArray(78, $myArray); // 2
function asearch($key, $myArray) {
for ($i = 0; $i < sizeof($myArray); $i++) {
if ($myArray[$i][0] == $key) {
return $i;
}
}
return -1; # no match
}
Though, you'd probably want to restructure your array to:
$myarray = array(
'dogs' => 98,
'cats' => 56,
'buffaloes' => 78
);
And just do:
$myArray['buffaloes']; # 78
The only way you can do it is to iterate over every item and preform a Linear Search
$i = -1;
foreach ($myArray as $key => $item){
if ( $item[0] == 'buffaloes' ){
$i = $key;
break;
}
}
//$i now holds the key, or -1 if it doesn't exist
As you can see, it is really really inefficient, as if your array has 20,000 items and 'buffaloes' is the last item, you have to make 20,000 comparisons.
In other words, you need to redesign your data structures so that you can look something up using the key, for example a better way may be to rearrange your array so that you have the string you are searching for as the key, for example:
$myArray['buffaloes'] = 76;
Which is much much faster, as it uses a better data structure so that it only has to at most n log n comparisons (where n is the number of items in the array). This is because an array is in fact an ordered map.
Another option, if you know the exact value of the value you are searching for is to use array_search
I never heard of built in function. If you want something more general then above solutions you shold write your own function and use recursion. maybe array_walk_recursive would be helpful
You can loop over each elements of the array, testing if the first element of each entry is equal to "buffaloes".
For instance :
foreach ($myArray as $key => $value) {
if ($value[0] == "buffaloes") {
echo "The key is : $key";
}
}
Will get you :
The key is : 2
Another idea (more funny ?), if you want to whole entry, might be to work with array_filter and a callback function that returns true for the "bufalloes" entry :
function my_func($val) {
return $val[0] == "buffaloes";
}
$element = array_filter($myArray, 'my_func');
var_dump($element);
Will get you :
array
2 =>
array
0 => string 'buffaloes' (length=9)
1 => int 78
And
var_dump(key($element));
Gves you the 2 you wanted.