Find min/max values in a multidimensional array - php

I need to find the minimum and maximum in a multidimensional array in PHP, I have what I thought would work below but it keeps giving me a parse error, this is homework and I am not asking anyone to do it for me but I am a beginner and any help would be appreciated.
<?php
/* 2 dimensional array in PHP - strictly an array of arrays */
$multable[] = array("11", "12", "15", "22", "41", "42");
$multable[] = array("6", "7", "16", "17", "22", "23");
$multable[] = array("1", "15", "16", "20", "22", "3");
<table>
<?php
/* display a table from a 2D array */
for ($j=0;$j<3;$j++) {
print "<tr>";
for ($k=0;$k<6;$k++) {
echo "<td>",$multable[$j][$k],"</td>";
}
print "</tr>";
$max_value = 0;
foreach ($multable as $myMax) {
if ($max_value<$myMax) {
$max_value = $myMax;
}
}
echo $max_value;
?>
</table>

There is also a one-liner for that:
$max = max( array_map("max", $multable) );

use max() and min() functions of php.

Max:
<?php
$multable = array();
$multable[] = array("11", "12", "15", "22", "41", "42");
$multable[] = array("6", "7", "16", "17", "22", "23");
$multable[] = array("1", "15", "16", "20", "22", "3");
$max = -99999999;
foreach($multable as $sub){
$tempMax = max($sub);
if($tempMax > $max){
$max = $tempMax;
}
}
echo $max;
?>
You can figure out min :)

Your foreach iteration only does one dimension - each $myMax is one of your six element lists and not an individual scalar value. That's why your comparison doesn't work and the conditional is never true, you are trying to compare a scalar with an array. What you call $myMax would more appropriately be called $currentRow
This is ok because PHP has some functions to find the min and max of an array
http://us.php.net/manual/en/function.min.php
http://us.php.net/manual/en/function.max.php
$max_value = 0; $min_value = $multable[0][0];
foreach ($multable as $currentRow)
{
// COMPARE CURRENT ROW's MIN/MAX TO MIN/MAX_VALUE
// AND MAKE NEW ASSIGNMENT IF APPROPRIATE
}
Or hand this in and see what your teacher says:
function fComp ($f) {return function ($a,$b) use ($f) {return $f($a, $f($b));};}
$max = array_reduce($multable, fComp('max'), $multable[0][0]);
$min = array_reduce($multable, fComp('min'), $multable[0][0]);
echo "max: $max <br />";
echo "min: $min";
PS - in your earlier iterations to make the HTML table, it would be good form to lose the constants. Use count to get the length of the array instead - or better yet - use foreach like you do later on. (Even with foreach you would still need two of them nested, it doesn't iterate a 2-dimensional array element-by-element)

For Minimum value
echo min(array_map("min", $multable));
For Maximum Value
echo max(array_map("max", $multable));

$minArray = array();
foreach($arrayVal as $arrI=> $arrK)
{
if($arrK == min($arrayVal ) )
{
array_push($minArray , $arrayVal );
}
}
print_r($minArray);
Here you go :)

I do not recommend calling min() or max() on each subarray, then calling the function again on the reduced array. This is making too many calls and won't be most efficient.
Instead, flatten the indexed array just once with a spread&merge technique, then call min() or max() just once on the flattened array.
Code: (Demo)
$flat = array_merge(...$multable);
printf(
'Min: %d, Max: %d',
min($flat),
max($flat)
);
Output:
Min: 1, Max: 42
If you only need one or the other outcome, then don't bother with the temporary variable.
echo min(array_merge(...$multable));
Or
echo max(array_merge(...$multable));

Related

How can I access Json information in php using array indexing

I want to get all prices and add them. I was planning on using this to loop through the JSON but that would be another question. Am I approaching this the wrong way? Is there a better way to get the SUM of all prices?
I have found this answer which makes the same question but it does not work (duplicate: PHP: How to access array element values using array-index). Here is my JSON string.
{
"data": {
"230723": {
"2019-11-15": {
"price": 52,
"min_length_of_stay": 2,
"available": 1
},
"2019-11-16": {
"price": 90,
"min_length_of_stay": 2,
"available": 0
},
"2019-11-17": {
"price": 44,
"min_length_of_stay": 2,
"available": 0
},
"2019-11-18": {
"price": 44,
"min_length_of_stay": 2,
"available": 0
}
}
}
}
And here is my code:
$resultJson = file_get_contents('http://....');
$priceRange = json_decode($resultJson, true);
echo $priceRange['data']['230723']['2019-11-15']['price']; // working
//$priceRange = array_values($priceRange);
echo $priceRange[0][0][0][0]; // not working
The first echo works and return 52. The second echo does not work with or without the commented line (which was the answer to the duplicate question).
What am I missing?
Instead of changing the array from associative to numeric just loop through already existing array
Like this
$sum = 0;
$resultJson = file_get_contents('http://....');
$priceRanges = json_decode($resultJson, true);
foreach ($priceRanges['data'] as $id => $priceRange) {
if (!is_array($priceRange)) {
continue;
}
foreach ($priceRange as $date => $priceInfo) {
$sum += (isset($priceInfo['price']) ? intval($priceInfo['price']) : 0);
}
}
Well you know I hope that the data is in data and if you don't know the next key then reset helps. Then just get all price keys (hopefully you know this as well) and sum them:
$result = array_sum(array_column(reset($array['data']), 'price'));
Another way is using array_values on the first two levels:
$result = array_sum(array_column(array_values(array_values($array)[0])[0], 'price'));
To get each price the way you were trying to do you would need:
$result = array_values(array_values(array_values(array_values($array)[0])[0])[0])[0];
The code I wrote using Krzysztof Janiszewski answer, and works.
$sum = 0;
$priceRange = json_decode($resultJson, true);
foreach($priceRange as $item) {
foreach($item as $item2){
foreach($item2 as $item3){
$sum += $item3['price'];
}
}
}
echo $sum;

Loop through an array (+100 values) [duplicate]

This question already has answers here:
Show the two elements in foreach loop in every iteration? [duplicate]
(4 answers)
Closed 1 year ago.
This is my array:
$my_array = array("1", "2", "3", "4");
I want to achieve something like this:
1 vs 2
3 vs 4
Because the length of my array is only 4 it was easy for me to do this:
echo $my_array[0]." vs ".$my_array[1];
echo "<br>";
echo $my_array[2]." vs ".$my_array[3];
But how can I achieve this if my array has more than 100 values? I also want to account for odd numbers of array elements.
You can use a "for" loop, with an increment of two for every loop :
$len = count($my_array);
for($i=0; $i<$len; $i=$i+2) {
echo $my_array[$i]." vs ".$my_array[$i+1]."<br/>;
}
If you're not sure your array always contains an even number of indexes, you can add a condition in order to ignore the last case if there is no more pair to do.
$len = count($my_array);
for($i=0; $i<$len; $i=$i+2) {
if($i !== $len-1) {
echo $my_array[$i]." vs ".$my_array[$i+1]."<br/>;
}
}
Sure, for loop is the obvious answer, but there are more interesting ones ;)
$my_array = ["1", "2", "3", "4"];
$new_array = array_map(
function($v) {return isset($v[1]) ? "$v[0] vs $v[1]<br/>" : null; },
array_chunk($my_array, 2)
);
print_r($new_array);
Output:
Array
(
[0] => 1 vs 2<br/>
[1] => 3 vs 4<br/>
)
You can use a for loop to loop through the array.
$my_array = array("1", "2", "3", "4","5","6");
for ($x = 0; $x < sizeof($my_array); $x = $x+2) {
echo $my_array[0+$x]." vs ".$my_array[1+$x];
echo "<br>";
}

PHP How to loop randomly through an array of placeholders

I have a search input in my wordpress site, which I want to display different placeholdes each time the page been refreshed. So I will have an array of the different values, the function that will loop randomly through the array, and I think my problem is with the result. I'm using a plugin for the search input, so to define for example that the placeholder would say 'hello', I need to do:
$item['textinput']= "hello";
So I need the result to be:
$item['textinput']= $placeholders;
I am adding the whole code:
$placeholders = array("yo i hio", "and him", "nayo jones");
function randominputs($input){
$i=1;
while($i<=20){
$randNum = rand(1,100);
if($input==$i){
$item['textinput']= $placeholders;
}
$i++;
}
}
Thanks
Use array_rand:
$placeholder = $placeholders[array_rand($placeholders)];
I would suggest adding the sizeof() call to your code.
For example if I wanted to call a random result from an array you could try...
$arr = array("1", "2", "3", "4", "5", "6", "7");
$len = sizeof($arr) - 1; // account for the 0 position
$rand = rand(0,$len);
echo $arr[$rand];
You can also use like:
$placeholders = array("yo i hio", "and him", "nayo jones");
$randomPlaceholder = array_rand($placeholders);
$item["textinput"] = $randomPlaceholder[0];

How to order a given array in respect to another array considering it as substrings of data elements

How can I order a given array respectively to another array? Searching didn't find solution for this case. Briefly, an array that defines sorting order is like this (example):
$arrayorder = array("z", "q", "9", "1");
and an array I would like to sort using order defined by $arrayorder is like this:
$data = array("a1", "za", "19", "18", "qz", "qc", "qd", "zc", "zb", "u", "z9");
the output array should be:
$output = array ("z9", "za", "zb", "zc", "qc", "qd", "qz", "18", "19", "a1", "u");
In practice, $data array should be sorted based on order defined by $arrayorder, for example:
"zGray", "zBlue"
resulting order is:
"zBlue", "zGray"
Using the usort function allows you to define your own comparison function. Although not elegant, you could do something like
usort ($data, function ($a, $b)
{
$arrayorder = array("z", "q", "9", "1", "a", "u");
$ea = array_search(substr($a,0,1), $arrayorder );
$eb = array_search(substr($b,0,1), $arrayorder );
if ($ea == $eb) {
if ( $a == $b ) {
return 0;
}
else {
return ($a< $b) ? -1 : 1;
}
}
return ($ea< $eb) ? -1 : 1;
});
It's important to have all of the possible first chars in the arrayorder, or change the code to set some default being a high number to push them to the end of the sort order.

Simple PHP card dealer. Having trouble with the unset command when shuffling deck

I'm trying to learn PHP so I thought a simple card game would be a good start. I have 2 arrays, one for the suit and one for the card numbers, and I want to be able to represent every possible card combination in a random order, and then unset the array objects every time it shuffles to prevent duplication's. I have an example of the code below, but i'm receiving some errors on the unset function. Does anyone have a suggestion?
<?php
$suits = array ("clubs", "diamonds", "hearts", "spades");
$faces = array (1 => "A", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13");
$deck = array();
foreach ($suits as $suit) {
foreach ($faces as $face) {
$deck[] = $face . "|" . $suit;
unset($deck);
}
}
shuffle($deck);
$card_num=5;
for($j=0; $j<$card_num; $j++) {
echo array_pop($deck).'<br>';
}
?>
You don't need to unset($deck); while actually building up the $deck array.
Remove this line and your code should be fine.

Categories